Java学习笔记--时间对象和字符串对象的转化

DateFormat是一个抽象类用来将时间对象转化为字符串以及字符串转化为时间对象。
一般用SimpleDateFormat类(DateFormat的实现子类)来实现

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestDateFormatAndSimpleDateFormat {
    /*
    DateFormat是一个抽象类用来将时间对象转化为字符串以及字符串转化为时间对象。
    一般用SimpleDateFormat类(DateFormat的实现子类)来实现
     */
    public static void main(String[] args) throws ParseException {
        /*把时间对象按照“格式字符串指定格式”转成相应的字符串*/
        DateFormat df1=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        DateFormat df2=new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
        DateFormat df3=new SimpleDateFormat("yyyy-MM-dd");
        String str1=df1.format(new Date(4000000));
        System.out.println(str1);
        System.out.println(df2.format(new Date(4000000)));
        System.out.println(df3.format(new Date(4000000)));

        /*把字符串按照“格式字符串指定的格式”转成相应的时间对象*/
        DateFormat dt1=new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒");
        Date date=dt1.parse("2020年5月2日 11时37分45秒");
        System.out.println(date);

        /*测试其他的格式字符*/
        DateFormat df=new SimpleDateFormat("D");//今天是今年的第几天
        System.out.println(df.format(new Date()));

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值