I have a value like the following Mon Jun 18 00:00:00 IST 2012
and I want to convert this to 18/06/2012
How to convert this?
I tried this method
public String toDate(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date theDate = null;
//String in = date + "/" + month + "/" + year;
try {
theDate = dateFormat.parse(date.toString());
System.out.println("Date parsed = " + dateFormat.format(theDate));
} catch (ParseException e) {
e.printStackTrace();
}
return dateFormat.format(theDate);
}
but it throws following exception :
java.text.ParseException: Unparseable date: "Mon Jun 18 00:00:00 IST 2012"
I hope following program will solve your problem
java.time
The modern approach is with the java.time classes. These supplant the troublesome old legacy date-time classes such as
Date
,Calendar
, andSimpleDateFormat
.Parse as a
ZonedDateTime
.Extract a date-only object, a
LocalDate
, without any time-of-day and without any time zone.Dump to console.
See this code run live in IdeOne.com.
Poor choice of format
Your format is a poor choice for data exchange: hard to read by human, hard to parse by computer, uses non-standard 3-4 letter zone codes, and assumes English.
Instead use the standard ISO 8601 formats whenever possible. The java.time classes use ISO 8601 formats by default when parsing/generating date-time values.
Specify a proper time zone name in the format of
continent/region
, such asAmerica/Montreal
,Africa/Casablanca
, orPacific/Auckland
. Never use the 3-4 letter abbreviation such asEST
orIST
as they are not true time zones, not standardized, and not even unique(!). For example, your use ofIST
may be Irish Standard Time, Israel Standard Time (as interpreted by java.time, seen above), or India Standard Time.About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as
java.util.Date
,Calendar
, &SimpleDateFormat
.The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as
Interval
,YearWeek
,YearQuarter
, and more.You can also use a formula in excel in order to convert this type of date to a date type excel can read:
=DATEVALUE(CONCATENATE(MID(A1,8,3),MID(A1,4,4),RIGHT(A1,4)))
And you get:
12/7/2016
from:Wed Dec 07 00:00:00 UTC 2016
Just need to add: new SimpleDateFormat("bla bla bla", Locale.US)