I want to convert date: 2014-02-24T00:54:12.417-06:00 into IST format.
Till far I did:
String s = "2014-02-24T00:54:12.417-06:00";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZ");
Date d = formatter.parse(s);
TimeZone tx=TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tx);
System.out.println("Formatted date in IST = " + formatter.format(d));
String istDateFormat = formatter.format(d);
//Date da=formatter.format(d);
return istDateFormat;
But I am getting error:
Unparseable date: "2014-02-24T00:54:12.417-06:00"
DateFormat formatter = new SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss.SSSXXX"");
This is shold work, check the example in the Java Doc. There is : in between your TimeZone,
Your pattern suitable for 2001-07-04T12:08:56.235-0700 format.
The java.util.Date & .Calendar & SimpleDateFormat classes bundled with Java are notoriously troublesome. Avoid them.
The alternatives, Joda-Time and Java 8’s new java.time package solve your problem with less code. No need to bother with formatters and parsing as they both take ISO 8601 formatted strings directly.
Note one big difference: While java.util.Date objects have no time zone (effectively UTC/GMT), in both Joda-Time (DateTime) and java.time (ZonedDateTime) the date-time object knows its own assigned time zone and offset.
Joda-Time
String input = "2014-02-24T00:54:12.417-06:00";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone ); // Parse as a -06:00 value, then adjust 11.5 hours to India +05:30 time zone.
DateTime dateTimeUtc = dateTimeIndia.withZone( DateTimeZone.UTC ); // For comparison.
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeIndia: " + dateTimeIndia );
When run…
input: 2014-02-24T00:54:12.417-06:00
dateTimeUtc: 2014-02-24T06:54:12.417Z
dateTimeIndia: 2014-02-24T12:24:12.417+05:30
java.time (Java 8)
String input = "2014-02-24T00:54:12.417-06:00";
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTimeIndia = ZonedDateTime.parse( input ).withZoneSameInstant( zoneId ); // Parse as a -06:00 value, then adjust 11.5 hours to India +05:30 time zone.
ZonedDateTime zonedDateTimeUtc = zonedDateTimeIndia.withZoneSameInstant( ZoneOffset.UTC ); // For comparison.
Dump to console…
System.out.println( "input: " + input );
System.out.println( "zonedDateTimeUtc: " + zonedDateTimeUtc );
System.out.println( "zonedDateTimeIndia: " + zonedDateTimeIndia );
When run…
input: 2014-02-24T00:54:12.417-06:00
zonedDateTimeUtc: 2014-02-24T06:54:12.417Z
zonedDateTimeIndia: 2014-02-24T12:24:12.417+05:30[Asia/Kolkata]
Use this format: "yyyy-MM-dd'T'HH:mm:ss.SSSX"
You are using RFC time zone notation for your date format.
But your date string is ISO formatted
So it not able to parse your date.
Either do one of the following
change the formatter to have ISO format (i.e change ZZZ to XXX)
Or change you date string like 2014-02-24T00:54:12.417 -0600
Related
I tried converting this date the following way:
SimpleDateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSSZ");
but I got:
java.text.ParseException: Unparseable date: "2014-09-20 00:00:00 -0500" (at offset 20)
That "-0500" is the offset from UTC, in RFC822 format. You just want Z, without the SSS.
The Android SimpleDateFormat docs have it like this in the table:
Symbol: Z
Meaning: time zone (RFC 822)
Kind: (Time Zone)
Example: Z/ZZ/ZZZ:-0800 ZZZZ:GMT-08:00 ZZZZZ:-08:00
I would also personally specify a locale, as a matter of course: this is a machine-readable format rather than a human-oriented format, so I'd usually specify Locale.US:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z",
Locale.US);
String text = "2014-08-20 00:00:00 -0500";
System.out.println(format.parse(text));
The answer by Jon Skeet is correct.
Standard Date-Time Format
Here is some example code showing how to transform your string into compliance with ISO 8601.
String inputRaw = "2014-08-20 00:00:00 -0500";
String input = inputRaw.replaceFirst( " ", "T" ).replaceFirst( " ", "" ); // Replace first SPACE with a 'T', and delete second SPACE.
// input is "2014-08-20T00:00:00-0500".
Joda-Time
You can pass that compliant string directly to the constructor of DateTime in Joda-Time. Ditto for the equivalent in the java.time package in Java 8 (inspired by Joda-Time).
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // Specify it rather than have JVM's default applied.
DateTime dateTimeMontréal = new DateTime( input, timeZone );
DateTime dateTimeUtc = dateTimeMontréal.withZone( DateTimeZone.UTC );
Dump to console.
System.out.println( "inputRaw: " + inputRaw );
System.out.println( "input: " + input );
System.out.println( "dateTimeMontréal: " + dateTimeMontréal );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run…
inputRaw: 2014-08-20 00:00:00 -0500
input: 2014-08-20T00:00:00-0500
dateTimeMontréal: 2014-08-20T01:00:00.000-04:00
dateTimeUtc: 2014-08-20T05:00:00.000Z
I need to convert the timestamp from one timezone to another time zone and retrieve the time in milliseconds for that timezone.
I tried doing that below, but its not working out.
SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
localDateFormat.setTimeZone(TimeZone.getTimeZone("anothertimezone));
//Current Date Time in Local Timezone
System.out.println("Current Date and Time in local timezone: " + localDateFormat.format( new Date()));
Calendar calendar = localDateFormat.getCalendar();
System.out.println(calendar.getTime());
The calendar.gettime is printing the current machine's time and not the time based on the timezone.
Not quite sure what you are trying to achieve, but this prints the current time in CEST and IST:
SimpleDateFormat localDateFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
System.out.println("Current Date/Time in local timezone: " +
localDateFormat.format( new Date()));
localDateFormat.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println("Current Date/Time in IST timezone: " +
localDateFormat.format( new Date()));
You can also take a date and time in string form and parse it:
// create a string showing date and time in IST time zone
String istDateString = localDateFormat.format( new Date());
Date istDate = localDateFormat.parse( istDateString, new ParsePosition(0) );
System.out.println( istDateString + " parsed to " + istDate );
The default used in Date.toString is, of course, the local setting.
Adjusting time zones leaves you with the same milliseconds since epoch.
Using Joda-Time 2.3 is much easier than the notoriously troublesome java.util.Date and .Calendar classes bundled with Java. While a java.util.Date has no time zone, a DateTime object in Joda-Time does indeed know its own assigned time zone.
Here is some example code. All of these DateTime objects represent the same moment in the timeline of the Universe, that is, the same number of milliseconds since the Unix epoch (the beginning of 1970). To verify, call the getMillis method to extract the number of milliseconds.
String inputRaw = "2014-01-02 03:04:05";
String input = inputRaw.replace( " ", "T" ); // Convert to strict version of ISO 8601 standard format.
DateTimeZone timeZoneParis = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeParis = new DateTime( input, timeZoneParis ); // Interpret that string as being in a particular time zone.
DateTime dateTimeUtc = dateTimeParis.withZone( DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeParis.withZone( DateTimeZone.forID( "America/Montreal" ) );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeParis: " + dateTimeParis );
System.out.println( "dateTimeParis millis: " + dateTimeParis.getMillis() );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeUtc millis: " + dateTimeUtc.getMillis() );
System.out.println( "dateTimeMontréal: " + dateTimeMontréal );
System.out.println( "dateTimeMontréal millis: " + dateTimeMontréal.getMillis() );
When run…
input: 2014-01-02T03:04:05
dateTimeParis: 2014-01-02T03:04:05.000+01:00
dateTimeParis millis: 1388628245000
dateTimeUtc: 2014-01-02T02:04:05.000Z
dateTimeUtc millis: 1388628245000
dateTimeMontréal: 2014-01-01T21:04:05.000-05:00
dateTimeMontréal millis: 1388628245000
String dateTimePattern = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat sdf = new SimpleDateFormat(dateTimePattern);
Date startTime = sdf.parse("2014-03-14 04:16:58.666");
System.out.println(startTime);
Output
Fri Mar 14 04:16:58 CDT 2014
Why is not printing milliseconds?
The problem here is not that the milliseconds are not getting parsed, your startTime includes the milliseconds you have provided. The problem is that they are not getting printed.
You need to format your output if you want something other than the default format from Date#toString():
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
You can use your SimpleDateFormat to format your output too, which will give you milliseconds:
System.out.println(sdf.format(startTime));
You are printing startTime directly (e.g. the toString() from java.util.Date); if you want your output to match your specified DateFormat you could do -
String dateTimePattern = "yyyy-MM-dd HH:mm:ss.SSS";
SimpleDateFormat sdf = new SimpleDateFormat(dateTimePattern);
Date startTime = sdf.parse("2014-03-14 04:16:58.666");
System.out.println(sdf.format(startTime)); // <-- use the DateFormat.
Which will output
2014-03-14 04:16:58.666
The other answers are correct.
Avoid j.u.Date
You would have simpler code and none of that confusion if you used Joda-Time (or java.time package in Java 8) rather than the notoriously troublesome java.util.Date & .Calendar & java.text.SimpleDateFormat classes bundled with Java.
Joda-Time
Joda-Time has built-in automatic parsers for ISO 8601 formats. Your format would work if you replaced that space with a T.
Example code using Joda-Time 2.3…
String inputRaw = ( "2014-03-14 04:16:58.666" );
String input = inputRaw.replace( " ", "T" );
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( input, timeZone );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run…
input: 2014-03-14T04:16:58.666
dateTime: 2014-03-14T04:16:58.666+01:00
dateTimeUtc: 2014-03-14T03:16:58.666Z
I have a date string in this format:
String fieldAsString = "11/26/2011 14:47:31";
I am trying to convert it to a Date type object in this format: "yyyy.MM.dd HH:mm:ss"
I tried using the following code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
Date newFormat = sdf.parse(fieldAsString);
However, this throws an exception that it is an Unparsable date.
So I tried something like this:
Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString);
String newFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(date)
However, this new format is now in the 'String' format but I want my function to return the new formatted date as a 'Date' object type. How would I do this?
Thanks!
You seem to be under the impression that a Date object has a format. It doesn't. It sounds like you just need this:
Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString);
(You should consider specifying a locale and possibly a time zone, mind you.)
Then you've got your Date value. A format is only relevant when you later want to convert it to text... that's when you should specify the format. It's important to separate the value being represent (an instant in time, in this case) from a potential textual representation. It's like integers - there's no difference between these two values:
int x = 0x10;
int y = 16;
They're the same value, just represented differently in source code.
Additionally consider using Joda Time for all your date/time work - it's a much cleaner API than java.util.*.
The answer by Jon Skeet is correct and complete.
Internal to java.util.Date (and Date-Time seen below), the date-time value is stored as milliseconds since the Unix epoch. There is no String inside! When you need a textual representation of the date-time in a format readable by a human, either call toString or use a formatter object to create a String object. Likewise when parsing, the input string is thrown away, not stored inside the Date object (or DateTime object in Joda-Time).
Joda-Time
For fun, here is the (better) way to do this work with Joda-Time, as mentioned by Mr. Skeet.
One major difference is that while a java.util.Date class seems to have a time zone, it does not. A Joda-Time DateTime in contrast does truly know its own time zone.
String input = "11/26/2011 14:47:31";
// From text to date-time.
DateTimeZone timeZone = DateTimeZone.forID( "Pacific/Honolulu" ); // Time zone intended but unrecorded by the input string.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm:ss" ).withZone( timeZone );
// No words in the input, so no need for a specific Locale.
DateTime dateTime = formatterInput.parseDateTime( input );
// From date-time to text.
DateTimeFormatter formatterOutput_MontréalEnFrançais = DateTimeFormat.forStyle( "FS" ).withLocale( java.util.Locale.CANADA_FRENCH ).withZone( DateTimeZone.forID( "America/Montreal" ) );
String output = formatterOutput_MontréalEnFrançais.print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime as milliseconds since Unix epoch: " + dateTime.getMillis() );
System.out.println( "dateTime in UTC: " + dateTime.withZone( DateTimeZone.UTC ) );
System.out.println( "output: " + output );
When run…
input: 11/26/2011 14:47:31
dateTime: 2011-11-26T14:47:31.000-10:00
dateTime as milliseconds since Unix epoch: 1322354851000
dateTime in UTC: 2011-11-27T00:47:31.000Z
output: samedi 26 novembre 2011 19:47
Search StackOverflow for "joda" to find many more examples.
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("PST"));
cal.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date resultdate = new Date(cal.getTimeInMillis());
sdf.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println("String date:"+sdf.format(resultdate));
System.out.println("Date:"+sdf.parse(sdf.format(resultdate)));
output:
String date:2011-12-29 09:01:58 PM
Date:Fri Dec 30 10:31:58 IST 2011
Problem:
sdf.format(resultdate) returning correct date and time to as per timezone. But,
sdf.parse(sdf.format(resultdate)) not returning correct date and time to as per timezone, how to fix this problem?
The Date class is merely a thin wrapper around the number of milli-seconds past the 'epoch' (January 1, 1970, 00:00:00 GMT). It doesn't store any timezone information. In your last call you are adding a date instance to a String which implicitly calls the toString() method. The toString() method will use the default timezone to create a String representing the instance (as it doesn't store any timezone info). Try modifying the last line to avoid using the toString() method.
System.out.println("Date:" + sdf.format(sdf.parse(sdf.format(resultdate))));
Try using joda-Time api for your convenience. Example is here
Unfortunatley Java date returns time in GMT only. When ever you want display in front end or some where, you need to use the formated String generated in your step1.
try the below code will, it will work.
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("PST"));
cal.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date resultdate = new Date(cal.getTimeInMillis());
sdf.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println("String date:"+sdf.format(resultdate));
System.out.println("Date:"+sdf2.parse(sdf.format(resultdate)));
Three-Letter Time Zone Codes
Avoid using the three-letter time zone codes. They are neither standardized nor unique. For example, IST means both India Standard Time and Irish Standard Time. Furthermore, the codes are meant to distinguish Daylight Saving Time (DST) but that only confuses matters.
Use proper descriptive time zone names to retrieve a time zone object that encompasses DST and other issues.
Joda-Time
The java.util.Date & Calendar classes bundled with Java are notoriously troublesome. Avoid them. Use Joda-Time or the new java.time.* package bundled with Java 8.
In JodaTime, a DateTime object truly knows its own time zone (unlike java.util.Date). Usually we use the immutable classes in Joda-Time. So instead of changing the time zone in a DateTime object, we create a fresh new DateTime object based on the old but with a specified difference. A different time zone might be that difference.
Here is some example code.
DateTimeZone timeZone_India = DateTimeZone.forID( "Asia/Kolkata" );
DateTimeZone timeZone_Ireland = DateTimeZone.forID( "Europe/Dublin" );
DateTimeZone timeZone_US_West_Coast = DateTimeZone.forID( "America/Los_Angeles" );
DateTime now = new DateTime( timeZone_India );
System.out.println( "now in India: " + now );
System.out.println( "now in Ireland: " + now.withZone( timeZone_Ireland ) );
System.out.println( "now in US West Coast: " + now.withZone( timeZone_US_West_Coast ) );
System.out.println( "now in UTC/GMT: " + now.withZone( DateTimeZone.UTC ) );
When run…
now in India: 2014-02-10T13:52:27.875+05:30
now in Ireland: 2014-02-10T08:22:27.875Z
now in US West Coast: 2014-02-10T00:22:27.875-08:00
now in UTC/GMT: 2014-02-10T08:22:27.875Z
java.time
Same idea using the java.time classes which supplant Joda-Time.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now();
Apply a time zone.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
The instant and the zdt represent the same moment, the same point on the timeline. Each is seen through the lens of a different region’s wall-clock time.
Generate a String by either specifying a formatting pattern or by letting java.time automatically localize.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
Example:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );