java获取小时和分并比较_如何在Java中获取当前时刻的年,月,日,小时,分钟,秒和毫秒?...

小编典典

LocalDateTime now = LocalDateTime.now();

int year = now.getYear();

int month = now.getMonthValue();

int day = now.getDayOfMonth();

int hour = now.getHour();

int minute = now.getMinute();

int second = now.getSecond();

int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.

System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

或者,当您尚未使用Java

8时,请使用java.util.Calendar。

Calendar now = Calendar.getInstance();

int year = now.get(Calendar.YEAR);

int month = now.get(Calendar.MONTH) + 1; // Note: zero based!

int day = now.get(Calendar.DAY_OF_MONTH);

int hour = now.get(Calendar.HOUR_OF_DAY);

int minute = now.get(Calendar.MINUTE);

int second = now.get(Calendar.SECOND);

int millis = now.get(Calendar.MILLISECOND);

System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);

不管哪种方式,到目前为止都将打印:

2010-04-16 15:15:17.816

要转换int成String,请使用String#valueOf()。

如果您的意图 毕竟

是以一种人类友好的字符串格式来排列和显示它们,那么最好使用Java8的java.time.format.DateTimeFormatter(此处的教程),

LocalDateTime now = LocalDateTime.now();

String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);

String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);

String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));

System.out.println(format1);

System.out.println(format2);

System.out.println(format3);

Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!

String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);

String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);

String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);

System.out.println(format1);

System.out.println(format2);

System.out.println(format3);

无论哪种方式,都会产生:

2010-04-16T15:15:17.816

2010年4月16日,星期五,格林尼治标准时间15:15:17

20100416151517

2020-09-15

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值