Simple date formatting giving wrong time

后端 未结 4 1632
暗喜
暗喜 2021-01-20 05:57

I am trying to parse a String to a Date and it giving me right date where as time is wrong.

SimpleDateFormat formatter = new SimpleDateFormat(\"yyyy-MM-dd HH         


        
相关标签:
4条回答
  • 2021-01-20 06:26

    Try below code

    SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy hh:mm:ss z");
    String dateToStr = format.format(new Date());
    System.out.println("dateToStr=>" + dateToStr);
    
    try {
            Date strToDate = format.parse(dateToStr);
            System.out.println("strToDate=>" + strToDate);
    } catch (ParseException e) {
            e.printStackTrace();
    }
    
    0 讨论(0)
  • 2021-01-20 06:27

    Maybe its related to time zone issues, at what time zone is your input?, i'd suggest to make sure your paramater is on UTC timezone and then using formatter like this :

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm aaa");
    formatter .setTimeZone(TimeZone.getTimeZone("UTC"));
    
    0 讨论(0)
  • 2021-01-20 06:28

    Try this code you missed some lines of code

    SimpleDateFormat mFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm aa",  Locale.getDefault());
    mFormatter.setTimeZone(TimeZone.getTimeZone("India"));
    Date startDate = mFormatter.parse("2015-08-20 05:00 AM");
    

    This code working fine for me.

    0 讨论(0)
  • 2021-01-20 06:34

    It seems the problem was that your pattern String specified am/pm, but was using uppercase H's for the hour characters. These indicate a 24-hour clock, which obviously doesn't use am/pm. Change the hour characters to lowercase h's, which indicate the hour in am/pm (0-11).

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm aaa");
    

    The docs for SimpleDateFormat explain the various acceptable pattern characters.

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