SimpleDateFormat returns 24-hour date: how to get 12-hour date?

前端 未结 9 2293
一生所求
一生所求 2020-12-08 06:41

I want current time in millis and then to store it in 12 hour format but with this piece of code I am getting 24 hour format time.

long timeInMillis = System         


        
相关标签:
9条回答
  • 2020-12-08 07:06

    See code example below:

    SimpleDateFormat df = new SimpleDateFormat("hh:mm");
    String formattedDate = df.format(new Date());
    out.println(formattedDate);
    
    0 讨论(0)
  • 2020-12-08 07:09

    Yep, confirmed that simply using hh instead of HH fixed my issue.

    Changed from this:

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm aa");
    

    To this:

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
    

    You can still use HH to store the time if you don't want to bother storing and dealing with the AM/PM. Then when you retrieve it, use hh.

    0 讨论(0)
  • 2020-12-08 07:09

    Hi I tested below code that worked fine :

        long timeInMillis = System.currentTimeMillis();
        Calendar cal1 = Calendar.getInstance();
        cal1.setTimeInMillis(timeInMillis);
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
        dateFormat.format(cal1.getTime());
    
    0 讨论(0)
提交回复
热议问题