Date,LocalDate,时间戳获取时间的方式与转换

it2022-05-05  112

开发过程中总会涉及到时间转换问题,下面描述了几种时间的获取方式以及转换: 1.Date日期格式化 2.LocalDate获取年月日 3.时间戳的获取 4.Date转换时间戳 5.时间戳转Date


1.Date日期格式化

public static void main(String[] args){ SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String sdfTime = sdf.format(new Date()); System.out.println("当前格式化时间: "+sdfTime); }

输出结果为:

当前格式化时间:2018-05-31 20:26:49

2.LocalDate获取年月日

public static void main(String[] args){ LocalDate lldate = LocalDate.now(); System.out.println("LocalDate生成的时间:"+"\n"+"本年中的第"+lldate.getDayOfYear()+"天\n本月的第"+lldate.getDayOfMonth()+"天\n本周周"+lldate.getDayOfWeek()); }

输出结果为:

LocalDate生成的时间: 本年中的第199天 本月的第18天 本周周THURSDAY

3.时间戳的获取

public static void main(String[] args){ Long timestamp = System.currentTimeMillis(); System.out.println("当前时间的时间戳13位: "+timestamp); System.out.println("当前时间时间戳10位: "+Long.valueOf(timestamp/1000)); }

输出结果为:

当前时间的时间戳13位: 1563443626049 当前时间时间戳10位: 1563443626

4.Date转换时间戳

public static void main(String[] args){ //注意l变量需要用long定义 SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Long l = 1563429965706000l; String ds = sdf.format(new Date(Long.parseLong(String.valueOf(l/1000)))); String ds1 = sdf.format(new Date(Long.parseLong(String.valueOf(timestamp)))); System.out.println("date转时间戳: "+ds); }

输出结果为:

date转时间戳: 2019-07-18 14:06:05

5.时间戳转Date

public static void main(String[] args){ SimpleDateFormat sdfTime =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Long ts=Long.valueOf(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sdfTime,new ParsePosition(0)).getTime()); System.out.println("时间戳转date: "+ts);

输出结果为:

时间戳转date: 1563443625000

最新回复(0)