Вопрос

I am trying to replace the hyphens with a forward slash, but it results to an unparseable date exception

    String test = "2014-04-01 05:00:00";
    Date date = new SimpleDateFormat("YYYY/MM/dd hh:mm:ss", Locale.ENGLISH).parse(test);
    System.out.println(date);

I have the necessary values for it to be converted, can someone tell me why it returns an error? Plus I wanted to append an am/pm marker at the end of the format, is this possible?

Это было полезно?

Решение

You need to parse String to Date first in correct format as input String

yyyy-MM-dd HH:mm:ss

then you can use format() to print it in other format

yyyy/MM/dd hh:mm:ss

and don't expect toString() method of Date class return formatted value, it is fixed implementation

Другие советы

From SimpleDateFormat:

Letter   Date or Time Component <br />
  y      Year <br />
  Y      Week year
  H      Hour in day (0-23)
  h      Hour in am/pm (1-12)

So, use yyyy for year and HH for hours in the day. Also, you're separating the fields by -, not by /:

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse(test);

After doing this, as @JigarJoshi suspects, you can format your Date to look with another format:

String dateInDesiredFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss a", Locale.ENGLISH).format(date);

Or written as a complete block of code:

DateFormat parse = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH);
DateFormat format = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss a", Locale.ENGLISH);

String test = "2014-04-01 05:00:00";
Date date = parse.parse(test);
System.out.println(format.format(date));

Produces the following output:

2014/04/01 05:00:00 AM
String test = "2014-04-01 05:00:00";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
Date oldDate = formatter.parse(test);
formatter.applyPattern("yyyy/MM/dd HH:mm:ss a");
Date newDate = formatter.parse(formatter.format(oldDate));
System.out.println(formatter.format(newDate));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top