I am trying to get a format like this:
2013-06-15-17-45
I do the following in my code:
Date d = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("YYYY_MM_DD_HH_mm");
String fileName = "D:\\"+ft.format(d)+".csv";
But I don't get the DD right. It creates a file with a name like this:
D:\\2013_12_340_13_53.csv
Capital "D" is day of year; lowercase "d" is day of month (SimpleDateFormat javadocs). Try:
SimpleDateFormat ft = new SimpleDateFormat ("yyyy_MM_dd_HH_mm");
Also, capital "Y" is "week year"; usually lowercase "y" ("year") is used.
The answer by rgettman is correct.
Joda-Time
Here's the same kind of code, but using Joda-Time 2.3 with Java 7.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTime now = new DateTime();
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy_MM_dd_HH_mm" );
System.out.println( "now ISO 8601 format: " + now.toString() );
System.out.println( "now in special format: " + formatter.print( now ) );
When run…
now ISO 8601 format: 2013-12-06T20:02:52.070-08:00
now in special format: 2013_12_06_20_02
Suggestion: ISO 8601 Style
I do the same kind of date-time in labeling files and folders. I suggest using a format closer to the standard ISO 8601 format.
Joda-Time has a built-in format close to what we need, dateHourMinute() on ISODateTimeFormat class.
For use with file systems, we should avoid using slash (Unix), backslash (MS Windows), and colon (Mac) characters. By starting with ISO format, we have no slash or backslash characters. That leaves only the colons from the time portion, to be removed with a call to replaceAll method of String class in Java.
You may wish to replace the T as well.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTime now = new DateTime();
System.out.println( "now: " + now );
DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinute();
String formatted = formatter.print( now ).replaceAll( ":", "." ).replaceAll( "T", "_" );
System.out.println( "formatted: " + formatted );
When run…
now: 2013-12-06T21:10:07.382-08:00
formatted: 2013-12-06_21.10
UTC
Furthermore, for server-side or other serious work consider converting to UTC rather than your local time to avoid ambiguity.
DateTime now = new DateTime();
System.out.println( "now: " + now );
DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinute();
String formatted = formatter.print( now.toDateTime( DateTimeZone.UTC ) ).replaceAll( ":", "." ).replaceAll( "T", "_" ) + "Z";
System.out.println( "formatted: " + formatted );
When run…
now: 2013-12-06T21:21:00.128-08:00
formatted: 2013-12-07_05.21Z
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'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.
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 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
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));