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

前端 未结 9 2292
一生所求
一生所求 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 06:48

    Simply follow the code

    public static String getFormatedDate(String strDate,StringsourceFormate,
                                         String destinyFormate) {
        SimpleDateFormat df;
        df = new SimpleDateFormat(sourceFormate);
        Date date = null;
        try {
            date = df.parse(strDate);
    
        } catch (ParseException e) {
            e.printStackTrace();
        }
    
        df = new SimpleDateFormat(destinyFormate);
        return df.format(date);
    
    }
    

    and pass the value into the function like that,

    getFormatedDate("21:30:00", "HH:mm", "hh:mm aa");
    

    or checkout this documentation SimpleDateFormat for StringsourceFormate and destinyFormate.

    0 讨论(0)
  • 2020-12-08 06:55

    Change HH to hh as

    long timeInMillis = System.currentTimeMillis();
    Calendar cal1 = Calendar.getInstance();
    cal1.setTimeInMillis(timeInMillis);
    SimpleDateFormat dateFormat = new SimpleDateFormat(
                                    "dd/MM/yyyy hh:mm:ss a");
    dateforrow = dateFormat.format(cal1.getTime());
    

    Note that dd/mm/yyyy - will give you minutes instead of the month.

    0 讨论(0)
  • 2020-12-08 06:55

    You can try it like this

      Calendar c= Calendar.getInstance();
    
      SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
      String str=sdf.format(c.getTime());
    
    0 讨论(0)
  • 2020-12-08 06:57
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
    

    use hh in place of HH

    0 讨论(0)
  • 2020-12-08 06:59

    I re-encounter this in the hard way as well. H vs h, for 24-hour vs 12 hour !

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

    Referring to SimpleDataFormat JavaDoc:

    Letter | Date or Time Component | Presentation | Examples
    ---------------------------------------------------------
       H   |  Hour in day (0-23)    |    Number    |    0
       h   |  Hour in am/pm (1-12)  |    Number    |    12
    
    0 讨论(0)
提交回复
热议问题