简体   繁体   中英

How to convert string date to Date object as per the System's Regional date time format settings?

In my project,i am using object of Date class, for example

Date date = Date(dateInStringForm);[Though it is deprecated]

It is working perfect with IST[Indian Standard Time] but when i change the settings in Region & Language in control panel [Operating system : Windows7] to any other country for example, portugal then it is throwing java.lang.IllegalArgumentException . How can we make this conversion generic ?

Following is my trial example code,

import java.util.Date;

public class GenericDateTime {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
   //  Date date = new Date("Jan 20, 2015 3:19:52 PM"); //Indian Standard Time Format
    Date date = new Date("20/Jan/2015 15:19:51"); //Portugese Time Format
    System.out.println("Date Object Form--->>>" + date);
}

}

Its has nothing to do with Timezone. You're giving a different format than a Date() would allow and can parse. There is no generic way that will accept any kind of date format without not knowing the format before converting.

So to accept any specific format you can use SimpleDateFormat .

     public static void main(String[] args) {

        SimpleDateFormat dateFormat= new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        try {
            Date date = dateFormat.parse("20/Jan/2015 15:19:51");
            System.out.println(date);
        } catch (ParseException e) {

            e.printStackTrace();
        }


  }

Instead of passing date as String you can use SimpleTimeFormat to specify date format and pass date string as UTC time. If you are free to use external libs Joda Time would be best option for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM