Converting String Format Date for Date Object

情到浓时终转凉″ 提交于 2019-12-24 22:24:16

问题


I am getting a Date format in String as Output like this.

Fri May 18 00:00:00 EDT 2012

I need to Convert this to a Date Object. What approach shall I use?

Thank you.

This is the program i used.

import java.util.*;
import java.text.*;

public class DateToString {
    public static void main(String[] args) {
        try {
            DateFormat formatter ;
            Date date ;
            formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss 'EDT' yyyy ");
            date = (Date)formatter.parse("Fri May 18 00:00:00 EDT 2012");
            String s = formatter.format(date);
            System.out.println("Today is " + s);
        } catch (ParseException e) {
            System.out.println("Exception :"+e); 
        }
    }
}

回答1:


Use SimpleDateFormat and implementations to get a date displayable in a format you want.

Example:

String myDateString = "Fri May 18 00:00:00 EDT 2012";
SimpleDateFormat dateFormat = new SimpleDateFormat();
dateFormat.applyPattern( "EEE MMM dd HH:mm:ss z yyyy" );

try {
    Date d = dateFormat.parse( myDateString );
    System.out.println( d ); // Fri May 18 00:00:00 EDT 2012

    String datePattern1 = "yyyy-MM-dd";
    dateFormat.applyPattern( datePattern1 );
    System.out.println( dateFormat.format( d ) ); // 2012-05-18

    String datePattern2 = "yyyy.MM.dd G 'at' HH:mm:ss z";
    dateFormat.applyPattern( datePattern2 );
    System.out.println( dateFormat.format( d ) ); // 2012.05.18 AD at 00:00:00 EDT

    String datePattern3 = "yyyy.MM.dd G 'at' HH:mm:ss Z";
    dateFormat.applyPattern( datePattern3 );
    System.out.println( dateFormat.format( d ) ); // 2012.05.18 AD at 00:00:00 -400
}
catch ( Exception e ) { // ParseException
    e.printStackTrace();
}



回答2:


Have a look at: java.text.SimpleDateFormat Java API

SimpleDateFormat dateParser = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", 
    Locale.US);
Date date = dateParser.parse("Fri May 18 00:00:00 EDT 2012");

Update: note to self, locale can be important.




回答3:


Use SimpleDateFormat with the following pattern:

EEE MMM dd HH:mm:ss 'EDT' YYYY

This doesn't worry about Timezone, Alternatively, with timezone inclusion: (untested) EEE MMM dd HH:mm:ss z YYYY (it's a lowercase z). Bear in mind, I haven't tested it yet (as I'm on my way home from work).



来源:https://stackoverflow.com/questions/10787281/converting-string-format-date-for-date-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!