Converting string to date with timezone

前端 未结 5 1639
温柔的废话
温柔的废话 2020-12-05 10:58

I have a string in the pattern yyyy-MM-dd hh:mm a and i can get the time zone object separately in which the above string represents the date.

I want to convert this

5条回答
  •  庸人自扰
    2020-12-05 11:34

    Undoubtedly, the format which is generally used will be of a form 2014-10-05T15:23:01Z (TZ)

    For that one has to use this code

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    String dateInString = "2014-10-05T15:23:01Z";
    
     try {
    
         Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
         System.out.println(date);
    
     } catch (ParseException e) {
         e.printStackTrace();
     }
    

    Its output will be Sun Oct 05 20:53:01 IST 2014

    However, I am not sure why we had to replaceAll "Z" if you do not add replaceAll the program will fail.

提交回复
热议问题