Simpledateformat is not parsing milliseconds - java

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

Related

What is the Time format for this "date": "2014-08-20 00:00:00 -0500"?

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

Convert mediumDate() to other format (with Locale) on Joda-Time

I've a problem to convert a date in other format in java (I'm using Joda-Time). In fact, I've a formatted local date as is:
24/giu/14 (Italian format date...but other local formats are possible)
I would like to see this in output (using Locale format date):
24/06/2014
I tried to build a sample code, but doesn't works...what am I doing wrong?
public String DateConvertFromMediumFormatToSlash (String date)
{
DateTimeFormatter dtf = DateTimeFormat.mediumDate().withLocale(Locale.getDefault());
LocalDate dt = dtf.parseLocalDate(date);
return dt.toString(); // output: 2014-06-24
}
Your question is confusing with regards to what you have as input and what you want as output.
Italy Uses Hyphens, Not Slashes
But one problem seems to be the slashes. Joda-Time expects hyphens not slashes. Here is some example code using Joda-Time 2.3 showing you what a LocalDate looks like as a String using the medium format for Locale of Italy.
LocalDate localDate = new LocalDate( 2014, 6, 24 );
System.out.println( "localDate: " + localDate );
DateTimeFormatter formatter = DateTimeFormat.mediumDate().withLocale( Locale.ITALY );
System.out.println( "output: " + formatter.print( localDate ) );
When run…
localDate: 2014-06-24
output: 24-giu-2014
Define A Formatter For Slashes
So if you want to parse/generate a string with slashes instead of the hyphens expected for Locale of Italy, you must explicitly define such a formatter.
String input = "24/giu/14";
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "dd/MMM/yy").withLocale( Locale.ITALY );
LocalDate localDate = formatterInput.parseLocalDate( input );
System.out.println( "localDate: " + localDate );
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "dd/MM/yy").withLocale( Locale.ITALY ); // Locale not needed here, but it's a good habit to specify.
String output = formatterOutput.print( localDate );
System.out.println( "Output: " + output );
When run…
localDate: 2014-06-24
Output: 24/06/14
By the way, using two digits for the year is asking for trouble IMHO.

Unparseable date: "2014-02-24T00:54:12.417-06:00" in java

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

Java converting a Date to a different format

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.

Convert miliseconds to date and time and format by locale

How can I convert milliseconds to a time and date string and format it correctly like the user expects it to be?
I did the following:
((SimpleDateFormat)DateFormat.getDateInstance(DateFormat.DEFAULT,Locale.getDefault())).format(new Date(Long.parseLong(timeInMilliseconds)));
Which seems to work, but I only get the date with this method.
Edit:
To clearify, I need to get the time/date pattern from system somehow to give each user his common format
Now I combined your solutions with mine and it seems to work like I expect.
private String getFormattedDateTimeString(Context context, String timeInMilliseconds) {
SimpleDateFormat dateInstance = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
SimpleDateFormat timeInstance = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.getDefault());
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(timeInMilliseconds));
String date = dateInstance.format(calendar.getTime());
String time = timeInstance.format(calendar.getTime());
return date + " " + time;
}
Why the hell do I get downvotes for this question???
All the other answers are missing the point that the string representation of the date-time needs to be localized.
Joda-Time
The Joda-Time 2.3 library makes this work much easier.
Joda-Time leverages a java.util.Locale to determine proper formatting of a date-time's string representation. The DateTimeFormat class offers an option for "style" pattern as a way of generating a DateTimeFormatter. You specify a two character style pattern. The first character is the date style, and the second character is the time style. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be omitted by specifying a style character '-'.
If you do not specify a Locale or time zone, the JVM's default will be used.
Locale
To create a java.util.Locale, you need:
Language code (either, see combined list)
ISO 639 alpha-2
ISO 639 alpha-3
Country Code (either)
ISO 3166 alpha-2 country code
UN M.49 numeric-3 area code
Example Code
// Simulate input.
long millisecondsSinceEpoch = DateTime.now().getMillis();
// Proceed with a 'long' value in hand.
DateTime dateTimeUtc = new DateTime( millisecondsSinceEpoch, DateTimeZone.UTC );
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Riyadh" );
DateTime dateTimeRiyadh = dateTimeUtc.withZone( timeZone );
// 'ar' = Arabic, 'SA' = Saudi Arabia.
java.util.Locale locale = new Locale( "ar", "SA" ); // ( language code, country code );
DateTimeFormatter formatter = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).withZone( timeZone );
String output = formatter.print( dateTimeUtc );
Dump to console…
System.out.println( "millisecondsSinceEpoch: " + millisecondsSinceEpoch );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeRiyadh: " + dateTimeRiyadh );
System.out.println( "output: " + output );
When run…
millisecondsSinceEpoch: 1392583624765
dateTimeUtc: 2014-02-16T20:47:04.765Z
dateTimeRiyadh: 2014-02-16T23:47:04.765+03:00
output: 16 فبراير, 2014 AST 11:47:04 م
Leaving your code as is, just change:
Instead of
getDateInstance
try
getDateTimeInstance
Or, you'd better use:
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
String datetime = fmt.format(cal.getTimeInMillis());
Use this...
String dateFormat = "dd/MM/yyyy hh:mm:ss.SSS";
// Create a DateFormatter object for displaying date in specified format.
DateFormat formatter = new SimpleDateFormat(dateFormat);
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
String formatedDate = formatter.format(calendar.getTime());
Try this
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");// you can rearange it as you like
cal.setTimeInMillis(timeInMilliseconds); //convert the time in milli to a date
String date = format.format(cal.getTime());// here you get your time formated
Why on earth do you want to use a calendar object???? It's just a waste of resources.
// Create a DateFormatter object for displaying date in specified format.
DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String formatedDate = myDateFormat.format(new Date(timeInMilliseconds));

Categories