JAVA-日期处理-LocalDate-时区


 

三种时区表示方式,LocalDate转成字符串日期和ts的方法

LocalDateTime localDateTime = null;
//时区写法1:
String timezone = "Asia/Shanghai";
//###### 字符串时间转ts
ZoneId zoneId = ZoneId.of(timezone);
localDateTime = LocalDateTime.parse("2018-06-26 16:29:42", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
long milliSecond = localDateTime.atZone(zoneId).toInstant().toEpochMilli();
System.out.println("milliSecond:" + milliSecond);
//###### ts转字符串时间
Instant instant = Instant.ofEpochMilli(milliSecond);
String date = LocalDateTime.ofInstant(instant, zoneId).toString();
System.out.println("date:" + date);
/**********************************************************************************/
//时区写法2:
timezone = "GMT+8";
//###### 字符串时间转ts
zoneId = ZoneId.of(timezone);
localDateTime = LocalDateTime.parse("2018-06-26 16:29:42", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
milliSecond = localDateTime.atZone(zoneId).toInstant().toEpochMilli();
System.out.println("milliSecond:" + milliSecond);
//###### ts转字符串时间
instant = Instant.ofEpochMilli(milliSecond);
date = LocalDateTime.ofInstant(instant, zoneId).toString();
System.out.println("date:" + date);
/**********************************************************************************/
//时区写法3:
timezone = "+8";
//###### 字符串时间转ts
zoneId = ZoneId.of(timezone);
localDateTime = LocalDateTime.parse("2018-06-26 16:29:42", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
milliSecond = localDateTime.atZone(zoneId).toInstant().toEpochMilli();
System.out.println("milliSecond:" + milliSecond);
//###### ts转字符串时间
instant = Instant.ofEpochMilli(milliSecond);
date = LocalDateTime.ofInstant(instant, zoneId).toString();
System.out.println("date:" + date);
/**********************************************************************************/

输出结果如下:

milliSecond:1530001782000
date:2018-06-26T16:29:42
milliSecond:1530001782000
date:2018-06-26T16:29:42
milliSecond:1530001782000
date:2018-06-26T16:29:42


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM