Most programming languages have a concept of "date/time" representation, which represents some point in time and allows the application of rules, such as time zones and leap years/seconds and other oddities to be applied.
When parsing a String
value, you must know the format that the String
is in, let's face it, what does 3/3/3
mean?
Java 8 replaced the existing Date
/Calendar
API which a much richer and less error prone API and you should make use of it as much as possible.
The first step is to construct a DateTimeFormatter
of which represents the desired input format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
See the JavaDocs for more details on the specifiers.
Next, you want to parse the text using the formatter...
String text = "Wed Dec 02 00:00:00 ICT 2015";
ZonedDateTime zdt = ZonedDateTime.parse(text, formatter);
System.out.println(zdt);
nb: I've used a ZonedDateTime
because I want to carry over the time zone information, you could use a LocalDateTime
, but that would depend on your underlying needs
This will print 2015-12-02T00:00+07:00[Asia/Bangkok]
I expect that the date will have "YYYY-mm-DD" format
An important concept to get your head around is, the toString
value of the a date object has nothing to do with its underlying representation and only represents a human readable representation of the object.
To format the date value into something else, you need to use another DateTimeFormatter
...
String formattedDate = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(zdt);
System.out.println(formattedDate);
And the will print 2015-12-02