java converting date in string format to timestamp - java

I am trying to convert a date in this format: "Fri Mar 1, 2013 4:30 PM" to a
timestamp value in this format: yyyy-mm-dd hh:mm:ss.
example:
String str = 'Fri Mar 1, 2013 4:30 PM' should output: "2013-01-14 23:59:59"
Here is what I've tried:
String string = "January 2, 2010";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(date);
This outputs: Sat Jan 02 00:00:00 GMT+05:30 2010
Thanks in Advance

String str = "Fri Mar 1, 2013 4:30 PM";
SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd, yyyy hh:mm a");
Date date = sdf1.parse(str);
System.out.println("Date Object:" + date);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm a");
System.out.println("Formatted Date:" + sdf2.format(date));
Output:
Date Object: Fri Mar 01 16:30:00 EST 2013
Formatted Date: 2013-03-01 16:30 PM

Assuming you are getting date and time as Date. So, You need format method of SimpleDateFormatter. Explore more patterns in the API.
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
Date currDate = new Date();
System.out.println("Current Date: " + currDate);
System.out.println("Formatted Date: " + sdf.format(currDate));
}
Output:
Current Date: Wed Feb 06 13:15:19 IST 2013
Formatted Date: 2013-02-06 13:15:750
If you have date in string format, you need to parse it in Date first and then format it.
Example:
String str = "Fri Mar 1, 2013 4:30 PM";
SimpleDateFormat sdf2 = new SimpleDateFormat("E MMM dd, yyyy HH:mm a");
Date parsedDate = sdf2.parse(str);
System.out.println("Parsed Date: " + parsedDate);
sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS a");
System.out.println("Formatted Date: " + sdf2.format(parsedDate));
Output:
Parsed Date: Fri Mar 01 04:30:00 IST 2013
Formatted Date: 2013-03-01 04:30:00 AM

The two previous answers were good answers in 2013. Time is moving on, and so is the handling of time information in Java. If you can use Java 8, do yourself the favour of using the date and time classes in the new java.time package (also backported to Java 6 and 7 in the ThreeTen Backport):
String str = "Fri Mar 1, 2013 4:30 PM";
LocalDateTime ldt = LocalDateTime.parse(str,
DateTimeFormatter.ofPattern("EEE MMM d, uuuu h:mm a", Locale.ENGLISH));
This produces a time without time zone of 2013-03-01T16:30. To format it into the desired output format:
System.out.println(ldt.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss")));
This prints:
2013-03-01 16:30:00
Should your want your timestamp in UTC, you may convert from your computer’s time zone like this:
ldt.atZone(ZoneId.systemDefault()).toInstant()
Since I am in the Central European Time zone, on my computer it produces a point in time of 2013-03-01T15:30:00Z (where Z signifies UTC; Instant objects are always printed in UTC).
Link: ThreeTen Backport Home

Related

SimpleDateFormatter Unparseable date exception

I have a string date Wed, 30 Mar 2016 01:39:56 +0000 which i want to convert to the date format "yyyy-MM-dd"
Below are the lines of code i am trying to achieve it. But it is returning unparseable date exception
String date_s = "Wed, 30 Mar 2016 01:39:56 +0000";
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("MMM d, yyyy");
System.out.println(dt1.format(date));
Any advice?
Since Java 8, you can do it in one line with the java.time library.
LocalDateTime.parse("Wed, 30 Mar 2016 01:39:56 +0000", DateTimeFormatter.RFC_1123_DATE_TIME)
.format(DateTimeFormatter.ISO_LOCAL_DATE);
'Wed, 30 Mar 2016 01:39:56 +0000' is not in the right format for yyyy-MM-dd to parse it
If you want it to work, try this:
SimpleDateFormat in = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd");
Date date = in.parse("Wed, 30 Mar 2016 01:01:01 +0000");
String outdate = out.format(date);
System.out.println(outdate);
Ideone

Timezone becomes GMT although I am overriding the timezone

Here is my code snippet. My local timezone is "Asia/Mumbai".
SimpleDateFormat isoFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
Date date1 = isoFormat.parse("03/01/2016 09:01 AM");
isoFormat.setTimeZone(TimeZone.getTimeZone("Asia/Mumbai"));
isoFormat.applyPattern("dd MMM yyyy HH:mm:ss z");
System.out.println("Current Date and Time in IST time zone: " + isoFormat.format(date1));
But in the output I am getting:
Current Date and Time in IST time zone: 01 Mar 2016 03:31:00 GMT
Can anyone tell why overriding a timezone which is also my local timezone can change it to a GMT?
While the same code works perfectly ok for JST or SGT.
isoFormat.setTimeZone(TimeZone.getTimeZone("Asia/Singapore"));
isoFormat.applyPattern("dd MMM yyyy HH:mm:ss z");
System.out.println("Current Date and Time in SGT time zone: " + isoFormat.format(date1));
isoFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo"));
isoFormat.applyPattern("dd MMM yyyy HH:mm:ss z");
System.out.println("Current Date and Time in JST time zone: " + isoFormat.format(date1));
Output:
Current Date and Time in SGT time zone: 01 Mar 2016 11:31:00 SGT
Current Date and Time in JST time zone: 01 Mar 2016 12:31:00 JST
Check the ID's available for the TimeZone: http://www.mkyong.com/java/java-display-list-of-timezone-with-gmt/
Try with below code:
isoFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));

Can't convert string to date in Java, wrong timezone after conversion

I have an array of Strings with the dates e.g.:
Tue, 09 Feb 2016 14:07:00 GMT;
Tue, 09 Feb 2016 19:55:00 GMT.
Now I want to find the most recent date on this list. In order to do that, I try to deserialize these strings to java.util.Date objects and after that compare them.
The code sample of java.util.Date object generation:
strDate = "Tue, 09 Feb 2016 14:07:00 GMT";
DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
Date date;
try {
date = format.parse(strDate);
//Result: Tue Feb 09 16:07:00 IST 2016
System.out.println("Result: " + date.toString());
} catch(ParseException e) {
e.printStackTrace();
}
My questions:
Why is the result in IST 2016 time zone and not in GMT? What does the IST 2016 stand for? Is it India Standard Time or Irish Standard Time or Israel Standard Time?
The initial string is in EEE, dd MMM format, the SimpleDateFormat pattern is also in this format, thus, why the result is in EEE, MMM dd format?
How can get a java.util.Date object in the same timezone as the initial string, in my case — GMT?
Is the approach I'm using to find the most recent date in the list is OK or there is more convenient/modern way to do that in Java 8, e.g., with the usage of LocalDateTime?
You are relying to Date.toString() to print your date when you should format it to a String with a formatter. What you are seeing is just the default pattern of Date.toString(). What you must keep in mind is that a Date does not have a timezone. You are seeing the output with the IST timezone, this must be because the current locale for the JVM is set to some specific locale for which the timezone name is "IST".
With regard to your point 4, yes, you can do it much cleaner with Java Time API introduced in Java 8. You can create a List of your strings to parse, create a DateTimeFormatter to parse it, and keep the maximum date value.
public static void main(String[] args) {
List<String> dates = Arrays.asList("Tue, 09 Feb 2016 14:07:00 GMT", "Tue, 09 Feb 2016 19:55:00 GMT");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
ZonedDateTime maxDate = dates.stream()
.map(s -> ZonedDateTime.parse(s, formatter))
.max(ZonedDateTime::compareTo)
.get(); // or .orElse(null)
System.out.println(maxDate);
}
This code is using a ZonedDateTime to keep the time-zone of the incoming strings.
Your computer seems to be set to IST. To force GMT output, import java.util.TimeZone and do this in your try block:
format.setTimeZone(TimeZone.getTimeZone("GMT"));
date = format.parse(strDate);
System.out.println("Result: " + format.format(date));

Java - unparseable date, need format to match "GMT-0400"

I have the following Java:
DateFormat formatter = new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zZ (zzzz)", Locale.ENGLISH);
Calendar cal = Calendar.getInstance();
cal.set(2011, Calendar.APRIL, 1);
out.println(formatter.format(cal.getTime()));
out.println();
Date date;
try {
date = formatter
.parse("Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)");
} catch (ParseException e) {
out.println("Failed to parse date: " + e.getMessage());
e.printStackTrace(out);
}
This is in a servlet, and the Calendar-constructed date comes out as:
Fri Apr 01 2011 16:42:24 EDT-0400 (Eastern Daylight Time)
This looks like the same format as the date string I'm trying to parse, except for EDT-0400 versus the desired GMT-0400. The code fails when trying to parse the date string:
java.text.ParseException: Unparseable date: "Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)"
How can I parse such a string? This is coming from a JavaScript date in a Sencha Touch 1.1.1 model, stored in WebSQL local storage.
For some reason GMT-0400 isnt' working, and UTC-0400 is working. You can replace GMT with UTC.
Note that this part will be completely ignored - the timezone will be resolved from what's found in the brackets (at least on my machine, JDK 6)
I debugged SimpleDateFormat and it seems that it will only parse GMT-04:00 but not GMT-0400.
It will accept UTC-0400, however it will throw away the hours/minutes modifier and will incorrectly parse it as UTC. (This happens with any other timezone designation, except for GMT)
It will also parse -0400 correctly, so the most robust solution is probably to simply remove GMT from your date string.
The upshot of the story is that SimpleDateFormat is anything but simple.
Update: Another lesson is that I could've saved a lot of time by passing a ParsePosition object to the parse() method:
DateFormat formatter = new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zzzz", Locale.ENGLISH);
Date date;
ParsePosition pos = new ParsePosition( 0 );
date = formatter
.parse("Fri Apr 01 2011 00:00:00 UTC-0400", pos);
System.out.println( pos.getIndex() );
Will print out 28, indicating that the parsing ended at character index 28, just after UTC.

how to convert date in java

I am new in android .
I have to convert following date into this time stamp (Wed Oct 12 14:17:42 GMT+05:30 2011)
Thu, 27 May 2010 12:37:27 GMT
This is the date that I am getting from the server through the header. I have converted it into the String object. Now I have to convert it into the Date format like: Wed Oct 12 14:17:42 GMT+05:30 2011
Please could you help me how should I convert it into the (Wed Oct 12 14:17:42 GMT+05:30 2011) this format using timestamp.
Have a look at DateFormat or SimpleDateFormat which provide parse() and format() methods. DateFormat provides a bunch of standard formats whereas SimpleDateFormat allows you to provide your own format expression.
Example for your input date:
//note that you need the locale as well, since the weekdays and months are written in a specific language, English in that case
SimpleDateFormat parseFormat = new SimpleDateFormat( "E, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH );
SimpleDateFormat writeFormat = new SimpleDateFormat( "E MMM dd HH:mm:ss z yyyy", Locale.ENGLISH );
writeFormat.setTimeZone( TimeZone.getTimeZone( "GMT" ) );
Date tDate = parseFormat.parse( "Wed, 12 Oct 2011 14:17:42 GMT" );
System.out.println(writeFormat.format(tDate )); //Wed Oct 12 14:17:42 GMT 2011
Edit: If you want a more usable API, try JodaTime.

Categories