I have one date string in the form of:
"Sun Sep 18 00:05:35 GMT+07:00 2016"
I am getting this format from Media store Date Taken. How to convert it to Date object in java/android?
I have one date string in the form of:
"Sun Sep 18 00:05:35 GMT+07:00 2016"
I am getting this format from Media store Date Taken. How to convert it to Date object in java/android?
The date in String can be parsed into the existing date object using SimpleDateFormat
class. By creating SimpleDateFormat
object and specifying the date pattern in its constructor you will be able to parse your date stored in string.
For you particular case code will look like this:
SimpleDateFormat format = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy");
Date date = null;
try {
date = format.parse(dateAsString);
} catch (ParseException e) {
e.printStackTrace();
}
As it can be seen from the pattern:
EEE - Day of the week in three letters (e.g. Sun, Mon, Tue, Wed, Thu, Fri, Sat)
MMM - month of the year (between 0 and 11)
dd - day of the month
HH - hour (between 00 and 23)
mm - minutes (between 00 and 59)
ss - seconds (between 00 and 59)
z - TimeZone (in your case, General Time Zone - GMT)
yyyy - year
In addition, if you further want to pass this Date
object to some Calendar
object you will need to set time zone there too.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+07:00"));
calendar.setTime(date);
However, if you have your TimeZone changing then you can extract the timeZone part from the string:
String timeZone = dateAsString.substring(19, 28);
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timeZone));
calendar.setTime(date);
Just be careful with the starting and ending indexes of substring()
function