简体   繁体   中英

format date using SimpleDateFormat

I am getting parser Exception while parsing the below date using simple date format API.

  String inputTimeStamp = "2012/07/19 09:49:00 - GMT -08:00";
  java.text.SimpleDateFormat dateformate= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  effDate = dateformate.parse(inputTimeStamp);

Please help me out on this.

Change

java.text.SimpleDateFormat dateformate=
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

to

java.text.SimpleDateFormat dateformate=
    new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

You have slashes (/) in your inputTimeStamp

Because you are parsing a date which is in a different format then you have described it to the SimpleDateFormat . If effDate is of type String and should hold the formatted date, the following code might solve it, although there is not supposed to be an space between GMT and -08:00 .

 String inputTimeStamp = "2012/07/19 09:49:00 - GMT -08:00";
 SimpleDateFormat inputDateformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss - z"); 
 SimpleDateFormat dateformate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 effDate = dateformate.format(inputDateFormat.parse(inputTimeStamp));

I would highly recommend also joda time , especially when you want to do calculations on the date.

 String inputTimeStamp = "2012/07/19 09:49:00 - GMT -08:00";
 DateTimeFormatter inputDateformat = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss - z Z"); 
 DateTimeFormatter dateformate = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
 effDate = dateformate.print(inputDateFormat.parseDateTime(inputTimeStamp));

The pattern would be: yyyy/MM/dd HH:mm:ss - z where z is for General Time Zone. SimpleDateFormat .

Try this:

new SimpleDateFormat("yyyy/MM/dd HH:mm:ss - z");

See this FYR

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