Format a date String java

前端 未结 2 1559
梦如初夏
梦如初夏 2021-01-26 01:43

I have a date String like so :- Fri Oct 31 11:30:58 GMT+05:30 2014 I want to Convert it into 2014-10-31T6:00:00 which should be after adding the offset

相关标签:
2条回答
  • 2021-01-26 02:15

    This should do the task, i guess.

    public static void main(String args[]) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(format.format(new Date()));  
    }
    
    0 讨论(0)
  • 2021-01-26 02:21

    First you need a SimpleDateFormat with the pattern that matches your input String: "EEE MMM dd HH:mm:ss z yyyy". Take a look at: SimpleDateFromat API

        SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    

    Then you can parse the input String to get a corresponding Date object as follows:

        Date date = in.parse("Fri Oct 31 11:30:58 GMT+05:30 2014");
    

    Note that Date objects does not have timezone as part of its state. If you want to print the Date in UTC then you need another SimpleDateFormat to format and print the date in your required timezone.

        SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        out.setTimeZone(TimeZone.getTimeZone("UTC"));
        out.format(date);   
    

    Example: http://ideone.com/Wojec3

    public static void main (String[] args) throws java.lang.Exception
    {
        SimpleDateFormat in = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        out.setTimeZone(TimeZone.getTimeZone("UTC"));
    
        Date date = in.parse("Fri Oct 31 11:30:58 GMT+05:30 2014");
    
        System.out.println(out.format(date));
    }
    
    0 讨论(0)
提交回复
热议问题