日期操作类

日期操作类

Date日期操作类

  • 在Java中提供有java.util.Date类,这个类如果直接实例化就可以获取当前的日期时间。
public class Demo {
    public static void main(String[] args) throws Exception {
        Date date=new Date();
        System.out.println(date);
    }
}
  • Date类中只是对long数据的一种包装。所以Date类中一定提供有所谓的日期与long数据类型之间转换的方法:
1.long转为Date:public Date(long date)2.将Date转为longpublic long getTime()

范例:观察Date与long之间的转换

public class Demo {
    public static void main(String[] args) throws Exception {
        Date date = new Date();
        long current = date.getTime();
        current += 1 * 864000 * 1000;    //10天的毫秒数
        System.out.println(new Date(current));   //long转为Date
    }
}

SimpleDateFormat日期处理类

  • 在java.text包中提供有SimpleDateFormat程序类。该类是DateFormat的子类,在该类中提供有如下的方法:
1.【DateFormat继承】将日期格式化:public final String format​(Date date)2.【DateFormat继承】将字符串转为日期: public Date parse​(String source) throws ParseException;
  • 构造方法:public SimpleDateFormat​(String pattern);
  • 日期格式:年(yyyy)、月(MM)、日(dd)、时(HH)、分(mm)、秒(ss)、毫秒(SSS)
    范例:格式化显示
public class Demo {
    public static void main(String[] args) throws Exception {
        Date date = new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String str=sdf.format(date);
        System.out.println(str);
    }
}

范例:将日期转为Date

public class Demo {
    public static void main(String[] args) throws Exception {
        String birthday="1846-11-11 11:11:11.111";   //字符串的日期
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date date=sdf.parse(birthday);
        System.out.println(date);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值