Printing out datetime in a specific format in Java?

后端 未结 4 1252
抹茶落季
抹茶落季 2020-12-02 00:58

I want to print out datetime in java in a specific format. I have this C# code which prints out the datetime in this format.

DateTime value = new DateTime(2         


        
相关标签:
4条回答
  • 2020-12-02 01:14

    If you need date in 24 hour system then use this approach

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date custDate = new Date();
    System.out.println(sdf.format(custDate));
    

    Please note in 24 hour system there is no need to show AM/PM.

    If you want date in 12 hour system then use below approach

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
    Date custDate = new Date();
    System.out.println(sdf.format(custDate));
    

    "a" in the date format will help to show AM/PM.

    Please import below classes for above code to work

    java.text.SimpleDateFormat

    java.util.Date

    0 讨论(0)
  • 2020-12-02 01:17

    Please try to this one

    public void Method(Datetime time)
    {
        
        time.toString("yyyy-MM-dd'T'HH:mm:ss"));
    }
    
    0 讨论(0)
  • 2020-12-02 01:33

    Approach 1: Using java.time.LocalDateTime. (Strongly Preferred)

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    LocalDateTime now = LocalDateTime.now();
    System.out.println(dtf.format(now)); //2016/11/16 12:08:43
    

    Approach 2: Using java.util.Date.

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43
    

    Approach 3: Using java.util.Calendar.

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43
    
    0 讨论(0)
  • 2020-12-02 01:35
    LocalDate.of(2010, 1, 18).atStartOfDay().format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a"))
    

    or

    LocalDate.of(2010, 1, 18).atTime(12, 0, 0).format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss a"));
    

    if you want to add the time too

    0 讨论(0)
提交回复
热议问题