本文共 2563 字,大约阅读时间需要 8 分钟。
// 获取当前时间戳,msSystem.currentTimeMillis();// 获取指定时间戳的Date对象Date date1 = new Date(11111111111111L);// 缺省参数默认取当前时间戳Date date2 = new Date();// 获取时间戳date1.getTime();
Date的大部分方法都过时了,仅仅用new Date()来获取当前日期时间,如果要进行其它操作,则使用其它得日期时间类。
// 使用静态方法获取实例,默认取当前的时间日期Calendar calendar=Calendar.getInstance();// 设置指定字段calendar.set(Calendar.YEAR,2020);// 设置年月日calendar.set(2020,1,1);// 设置年月日时分秒calendar.set(2020,1,1,1,1,1);//设置Date类型calendar.setTime(new Date());// 获取指定字段calendar.get(Calendar.YEAR)// 0-11,0表示1月calendar.get(Calendar.MONTH)//一年中的第几周int weekYear = calendar.getWeekYear();//获取DateDate date = calendar.getTime();
//当前时间LocalDateTime ldt1=LocalDateTime.now();//指定时间LocalDateTime ldt2=LocalDateTime.of(2020,1,1,1,1,1);//获取指定字段的值int year = ldt1.getYear();
// 只格式化日期DateFormat df1 = DateFormat.getDateInstance();// 只格式化时间DateFormat df2 = DateFormat.getTimeInstance();// 格式化日期时间DateFormat df3 = DateFormat.getDateTimeInstance();// 均可指定格式,DateFormat类的常量,缺省时默认都是MEDIUM// 日期:SHORT => 2019/5/13 , MEDIUM => 2019年5月13日 , FULL => 2019年5月13日星期一DateFormat df4 = DateFormat.getDateInstance(DateFormat.SHORT);// 时间:SHORT => 下午10:16 , MEDIUM => 下午10:17:06 , FULL => 中国标准时间 下午10:18:44DateFormat df5 = DateFormat.getTimeInstance();// 日期格式、时间格式DateFormat df6 = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);Date date = new Date();// 格式化Date对象,返回StringString srt = df1.format(date);
SimpleDateForm是DateForm的子类,比DateForm更简单、强大。
// 指定格式,可以自定义格式。毫秒是 SSS SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");SimpleDateFormat sdf2 = new SimpleDateFormat("y年的第D天");// 格式化Date对象,返回字符串Date date = new Date();String str1 = sdf1.format(date);String str2 = sdf2.format(date);
占位符 | 描述 |
---|---|
y | 四位数年份 |
M | 月 |
d | 日 |
h | 时,12小时制 |
H | 时,24小时制 |
m | 分 |
s | 秒 |
S | 毫秒 |
D | 一年中的第几天 |
w | 一年中第几个星期 |
E | 一周中的第几天 |
SimpleDateFormat很常用,使用时需要注意2个问题
DateTimeFormatter相当于DateFormat、SimpleDateFormat的结合体
DateTimeFormatter df1 = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT); //格式化日期DateTimeFormatter df2 = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT); //格式化时间DateTimeFormatter df3 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT); //格式化日期时间DateTimeFormatter df4 = DateTimeFormatter.ofPattern("y-M-d H:m:s"); //自定义格式// 日期用LocalDate,时间用LocalTime,日期时间用LocalDateTimeLocalDateTime date = LocalDateTime.now();// 格式化,返回StringString format = df1.format(date);
转载地址:http://hgqlb.baihongyu.com/