Need to get current timestamp in Java

后端 未结 10 1740
南旧
南旧 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

    You can make use of java.util.Date with direct date string format:

    String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
    
    0 讨论(0)
  • 2020-12-25 10:27

    I did it like this when I wanted a tmiestamp

        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
    

    Hope it helps :) As a newbie I think it's self-explanatory

    I think you also need import java.text.SimpleDateFormat; header for it to work :))

    0 讨论(0)
  • 2020-12-25 10:29

    Try this single line solution :

    import java.util.Date;
    String timestamp = 
        new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss a").format(new Date());
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题