Need to get current timestamp in Java

后端 未结 10 1778
南旧
南旧 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:33

    Joda-Time

    Here is the same kind of code but using the third-party library Joda-Time 2.3.

    In real life, I would specify a time zone, as relying on default zone is usually a bad practice. But omitted here for simplicity of example.

    org.joda.time.DateTime now = new DateTime();
    org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy h:mm:ss a" );
    String nowAsString = formatter.print( now );
    
    System.out.println( "nowAsString: " + nowAsString );
    

    When run…

    nowAsString: 11/28/2013 11:28:15 PM
    

提交回复
热议问题