Need to get current timestamp in Java

后端 未结 10 1777
南旧
南旧 2020-12-25 09:47

I need to get the current timestamp in Java, with the format of MM/DD/YYYY h:mm:ss AM/PM,

For example: 06/01/2000 10:01:50 AM

I ne

10条回答
  •  忘掉有多难
    2020-12-25 10:24

    java.time

    As of Java 8+ you can use the java.time package. Specifically, use DateTimeFormatterBuilder and DateTimeFormatter to format the patterns and literals.

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("MM").appendLiteral("/")
            .appendPattern("dd").appendLiteral("/")
            .appendPattern("yyyy").appendLiteral(" ")
            .appendPattern("hh").appendLiteral(":")
            .appendPattern("mm").appendLiteral(":")
            .appendPattern("ss").appendLiteral(" ")
            .appendPattern("a")
            .toFormatter();
    System.out.println(LocalDateTime.now().format(formatter));
    

    The output ...

    06/22/2015 11:59:14 AM
    

    Or if you want different time zone…

    // system default
    System.out.println(formatter.withZone(ZoneId.systemDefault()).format(Instant.now()));
    // Chicago
    System.out.println(formatter.withZone(ZoneId.of("America/Chicago")).format(Instant.now()));
    // Kathmandu
    System.out.println(formatter.withZone(ZoneId.of("Asia/Kathmandu")).format(Instant.now()));
    

    The output ...

    06/22/2015 12:38:42 PM
    06/22/2015 02:08:42 AM
    06/22/2015 12:53:42 PM
    

提交回复
热议问题