Date localization in java using DateFormat.getDateInstance - java

I have a date which must be localized.
Below code returns 5/1/12 19:06:34 but the result i want is 05/01/12 19:06:34
Could you please tell me how to manage this.
private String localizeDate(String date){ //Format is 2012-05-01 19:30:49
Locale loc = DataContextHolder.getDataContext().getLocale();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", loc);
Date parsed=null;
try {
parsed = formatter.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, loc);
String localizedDate = df.format(parsed) + " " + date.substring(11, 13) + ":"
+ date.substring(14, 16) + ":"
+ date.substring(17, 19);
return localizedDate;
}

You can avoid leading zeros by reducing the number of consecutive pattern letters for that particular element. Multiple pattern letters in a row tell the date formatter that, at minimum, you want that many characters to express that value.
In your example, the following should resolve your problem.
new SimpleDateFormat("y-M-d H:m:s", loc);
Find more in the SimpleDateFormat documentation.
For clarity, see the following example.
SimpleDateFormat a = new SimpleDateFormat("yyyyy-MMMM-dddd HHH:mmmm:sssss");
SimpleDateFormat b = new SimpleDateFormat("y-M-d H:m:s");
System.out.println(a.format(new Date()));
// Prints 02012-June-0005 012:0027:00026
System.out.println(b.format(new Date()));
// Prints 12-6-5 12:27:26

Problems
You have multiple problems happening with your code.
Time-Zone
One problem is that you are localizing without handling time zone. The parsing will apply the JVM's default time zone. That means running on different computers with different time zone settings yields different results. Generally best to specify a time zone rather than rely on default.
Formatting, Not Localizing
Another problem is that if you are truly localizing, you would not be specifying the details of the format. You would let the locale drive the formatting, whatever is appropriate to that locale and to the user's own localization settings.
Avoid java.util.Date
Yet another problem is that you are using the java.util.Date class bundled with Java. That class, and its sibling java.util.Calendar, are notoriously troublesome. Avoid them. Use either the Joda-Time framework or the new java.time.* package in Java 8.
ISO 8601
Your input string is very close to the standard ISO 8601 format, like this: 2014-02-07T07:06:41+03:00. Your text is merely missing a T in the middle and a time zone offset.
The Joda-Time framework uses ISO 8601 by default. So replacing that space with a "T" lets you pass the string directly to a DateTime constructor. No need for a formatter and parsing, as the DateTime constructor will do that work for you automatically.
Note that including or omitting the time zone offset from the end of the string input changes the behavior of constructing a DateTime. Without an offset, the string is parsed as if it occurred at the specified time within the passed time zone (the 2nd argument, see code example below). On the other hand, if you do include an offset in your input, the string is parsed as if it occurred at the specified time in the offset's locality, and then adjusts the time to the passed time zone argument.
Joda-Time Example
Here is some example code in Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Istanbul" );
String inputOriginal = "2012-05-01 19:30:49";
String input = inputOriginal.replace( " ", "T" );
DateTime dateTime = new DateTime( input, timeZone );
// Or if your input is UTC/GMT (no time zone offset), pass a predefined DateTimeZone constant.
//DateTime dateTime = new DateTime( input, DateTimeZone.UTC );
We have our date-time value in hand. Now we proceed to generate formatted strings from that date-time. We do so by using Joda-Time’s Locale-sensitive formatting facility. Note that not only the format is localized, so is the text of the month and day names localized to appropriate language.
// Create a formatter from 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 ommitted by specifying a style character '-'.
java.util.Locale locale = new java.util.Locale( "tr", "TR" ); // Turkey chosen as an example.
String output_ShortShort = DateTimeFormat.forStyle( "SS" ).withLocale( locale ).print( dateTime );
String output_LongShort = DateTimeFormat.forStyle( "LS" ).withLocale( locale ).print( dateTime );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime in UTC/GMT: " + dateTime.toDateTime( DateTimeZone.UTC ) );
System.out.println( "output_ShortShort: " + output_ShortShort );
System.out.println( "output_LongShort: " + output_LongShort );
When run…
input: 2012-05-01T19:30:49
dateTime: 2012-05-01T19:30:49.000+03:00
dateTime in UTC/GMT: 2012-05-01T16:30:49.000Z
output_ShortShort: 01.05.2012 19:30
output_LongShort: 01 Mayıs 2012 Salı 19:30

You need to choose the appropriate date formatter. Please read the documentation here:
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Related

Convert UK time to South African time in Java

I have a football match date and time as UK time.
I am running this service in South Africa so it must display the fixture date and time as South African time. At the moment I am doing this:
int kickoffHour = fixture.getTime().getHours() + 2;
However - when it reaches end of March 2016 this will have to change again to "+ 1" instead of "+ 2". Now I can't keep changing this so I want something that will automatically pick up that its DST or BST and do the conversion.
I have tried something like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
Date date = sdf.parse(fixture.getDate() + " " + fixture.getTime());
But that gave me like 2am or something. My date in the database is: 2015-12-16 and the time in the database is 16:00:00 - after parsing I get Wed Dec 16 02:00:00 SAST 2015
Apparently you are referring to adjustments needed for Daylight Saving Time (DST). You should leave such work to a good date-time library rather than manage these details yourself.
Unfortunately, the old date-time classes bundled with early versions of Java are not good. While a valiant effort, they have proven to be troublesome and confusing, flawed in both design and implementation. Avoid java.util.Date/.Calendar and java.text.SimpleDateFormat.
java.time
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
By the way, best practice is to do all your business logic, data storage & exchange, and database work in UTC. Use zoned date-time values only when expected by the user or data sink. However, it appears you have been given a string in London time, so let's go with that.
String input = "2015-12-16 16:00:00"; // Local date-time in United Kingdom (London).
Use proper time zone names. Never use the 3-4 letter codes commonly seen as they are neither standardized nor unique.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "yyyy-MM-dd HH:mm:ss" );
Your string input lacks embedded info about its offset-from-UTC or time zone. So, we will assume the String represents local time in Europe/London. We communicate this assumption to the DateTimeFormatter, as it would otherwise interpret the incoming String as belonging to the JVM’s current default time zone. Note that java.time uses immutable objects, so rather than alter the formatter we generate a new instance based on values take from the old instance.
ZoneId zoneId_London = ZoneId.of ( "Europe/London" );
formatter = formatter.withZone ( zoneId_London ); // Specify the zone by which to interpret this date-time input string as it lacks any offset or time zone info.
ZonedDateTime zdt_UK = ZonedDateTime.parse ( input , formatter );
With a London date-time in hand, we can adjust into a South Africa time zone.
ZoneId zoneId_Johannesburg = ZoneId.of ( "Africa/Johannesburg" );
ZonedDateTime zdt_ZA = zdt_UK.withZoneSameInstant ( zoneId_Johannesburg );
Dump to console.
System.out.println ( "input: " + input + " in zone: " + zoneId_London + " = " + zdt_UK );
System.out.println ( "zdt_UK: " + zdt_UK + " adjusted to zone: " + zoneId_Johannesburg + " is: " + zdt_ZA );
input: 2015-12-16 16:00:00 in zone: Europe/London = 2015-12-16T16:00Z[Europe/London]
zdt_UK: 2015-12-16T16:00Z[Europe/London] adjusted to zone: Africa/Johannesburg is: 2015-12-16T18:00+02:00[Africa/Johannesburg]
Lastly, we do most of our work in UTC. For that, extract a Instant object which is a moment on the timeline in UTC.
Instant instant = zdt_ZA.toInstant();
if fixture.getDate() + " " + fixture.getTime() works fine, at the end you will get the String as "2015-12-16 16:00:00".
Then I simply format the returning date. Mine works fine..
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
Date date = sdf.parse("2015-12-16 16:00:00");
//Date date = sdf.parse("2016-03-31 23:50:50");
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("Africa/Johannesburg"));
System.out.println(df.format(date));
}
Output of this code is 2015-12-16 18:00:00
When I use commented date object, result was 2016-04-01 00:50:50
You can simply get the time values from the fixture and use calendar to auto convert your time zone. I am keeping in mind that your system timezone matches the expected output timezone. Please check the below code snipet, w/o using fixture object and using hard coded value.
Calendar cal = Calendar.getInstance();
cal.setTimeZone(java.util.TimeZone.getTimeZone("Europe/London"));
cal.set(Calendar.HOUR, 16);
cal.set(Calendar.MINUTE, 0);
cal.set(2015, 11, 24);
System.out.println(cal.getTimeZone());
System.out.println(cal.getTime()); //printing in IST (my local time)
You should have a Date object from your database.
If you want to print it, use your SimpleDateFormat setting its timezone to South Africa "Africa/Johannesburg" and it will work.
Date myDate;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Africa/Johannesburg"));
System.out.println(sdf.format(myDate));

Get Time stamp using Java GMT+5:30

I want Timestamp of given date.
using this code
public static String getTimestamp(String time)
{
DateFormat dfm = new SimpleDateFormat("dd-mm-yy hh:mm:ss");
long unixtime = 0;
dfm.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
try
{
unixtime = dfm.parse(time).getTime();
unixtime=unixtime/1000;
}
catch (ParseException e)
{
e.printStackTrace();
}
return ""+unixtime;
}
public static void main(String[] args)
{
System.out.println(getTimestamp("11-05-15 11:54:55"));
}
but when i enter this date 11-05-15 11:54:55 then program return me 1420957495 this timestamp which is timestamp of Jan (01) but i want May(06)
please help me
use this
DateFormat dfm = new SimpleDateFormat("dd-MM-yy hh:mm:ss");
Upper case MM is for month and lower case is for minute
Your Offset Is Invalid
A valid offset must include padded zero. Your offset string GMT+5:30 should be GMT+05:30 with a 0 before the 5.
Beyond that, the Answer by Meno Hochschild is correct and wise.
java.time
The java.util.Date/.Calendar and SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them.
Instead use java.time package found in Java 8 and later. Where lacking, use the Joda-Time library.
Here is some java.time code (Java 8).
First, parse your input into a "local" date-time value, meaning without any time zone attached. As there was no offset nor time zone included with the input, this value could apply to any particular locality.
String input = "11-05-15 11:54:55"; // Strongly recommend using 4-digit year whenever possible, as suggested in Meno Hochschild’s Answer.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd-MM-yy HH:mm:ss" ); // No need for Locale in this case, but always consider it.
LocalDateTime localDateTime = LocalDateTime.parse( input , formatter );
Next, we are presuming this value was meant to represent a moment in India. Let’s assign a time zone. We could assign merely an offset. But generally we should use a time zone. A time zone is an offset plus the past, present, and future set of rules for adjustments and anomalies such as Daylight Saving Time.
First we instantiate a time zone for India. Then we generate a ZonedDateTime based on the LocalDateTime while adding a time zone.
// Assign a time zone.
//ZoneId zoneId_plus_5_30 = ZoneId.of( "GMT+05:30" ); // You can use an offset, but know that a time zone is *more* than an offset.
ZoneId zoneIdKolkata = ZoneId.of( "Asia/Kolkata" ); // Better to use a time zone name if one is applicable. Ex: "Asia/Kolkata".
ZonedDateTime zonedDateTimeKolkata = ZonedDateTime.of( localDateTime , zoneIdKolkata );
For fun, let’s adjust the same moment to UTC and to Montréal.
ZonedDateTime zonedDateTimeUtc = zonedDateTimeKolkata.withZoneSameInstant( ZoneOffset.UTC );
ZonedDateTime zonedDateTimeMontréal = zonedDateTimeKolkata.withZoneSameInstant( ZoneId.of( "America/Montreal" ) );
Dump to console.
System.out.println( "Input: " + input );
System.out.println( "localDateTime: " + localDateTime );
System.out.println( "zonedDateTimeKolkata: " + zonedDateTimeKolkata );
System.out.println( "zonedDateTimeUtc: " + zonedDateTimeUtc );
System.out.println( "zonedDateTimeMontréal: " + zonedDateTimeMontréal );
When run.
Input: 11-05-15 11:54:55
localDateTime: 2015-05-11T11:54:55
zonedDateTimeKolkata: 2015-05-11T11:54:55+05:30[Asia/Kolkata]
zonedDateTimeUtc: 2015-05-11T06:24:55Z
zonedDateTimeMontréal: 2015-05-11T02:24:55-04:00[America/Montreal]
You should change your pattern. So far the accepted answer is right with respect to month. What is still missing is the pattern symbol for the hour of day. It should be H instead of h. Or if you prefer the English hour notation, you can use an additional letter "a" indicating AM/PM. So the final solution is:
DateFormat dfm = new SimpleDateFormat("dd-MM-yy HH:mm:ss");
or
DateFormat dfm = new SimpleDateFormat("dd-MM-yy hh:mm:ss a", Locale.ENGLISH);
And I recommend to use 4-digit-years to exclude any ambivalence using yyyy, by the way.

Convert date string to datetime object in Joda-Time?

I have a date string similar to:
"2014-04-10T00:00:00.000"
So I need to convert this to a Joda-Time DateTime object.
Here is my code :
String datePattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(datePattern);
currentCard.setStartDate("2014-04-10T00:00:00.000");
currentCard.setEndDate("2015-04-10T00:00:00.000");
DateTime startDateTime = dateFormatter.parseDateTime(currentCard.getStartDate());
DateTime endDateTime = dateFormatter.parseDateTime(currentCard.getEndDate());
if (startDateTime.isBeforeNow() && endDateTime.isAfterNow()) {
currentCard.setActive(true);
} else {
currentCard.setActive(false);
}
It tells me string is too short
I believe the correct syntax for the date pattern is "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". That way the Z is literally used.
While the other answers are correct, both the answers and your question are working too hard.
ISO 8601 Format
The format of the string in question, "2014-04-10T00:00:00.000", is standard ISO 8601 format. The DateTime class in Joda-Time has a built-in ISO 8601 parser/formatter built-in, used by default. So no need to instantiate a formatter. Merely pass the string to the constructor of DateTime.
Time Zone
Specify a time zone by which to interpret that date-time value. Otherwise the JVM's current default time zone is applied.
Example:
DateTimeZone timeZoneMontréal = DateTimeZone.forID( "America/Montreal" );
Example Code
Some example code using Joda-Time 2.5.
DateTime dateTime = new DateTime( "2014-04-10T00:00:00.000", DateTimeZone.UTC );
If that string represented a wall-time† moment in Québec rather than UTC, then specify that time zone by which the string should be understood while parsing.
DateTime dateTime = new DateTime( "2014-04-10T00:00:00.000", timeZoneMontréal );
Specify Format
As per the comment by Meno Hochschild, you may prefer to specify the expected format of the incoming String. Joda-Time has many pre-defined formatters built-in, as well as permitting you to define your own. In this case, our string lacks a time zone offset at the end, so we specify the formatter known as dateHourMinuteSecondFraction.
What if the incoming string is malformed or using an unexpected format? An exception is thrown. For robust code, trap for that exception.
String input = "2014-04-10T00:00:00.000";
DateTimeZone timeZoneMontréal = DateTimeZone.forID( "America/Montreal" );
DateTimeFormatter formatter = ISODateTimeFormat.dateHourMinuteSecondFraction().withZone( timeZoneMontréal );
DateTime dateTime = null;
try {
dateTime = formatter.parseDateTime( input );
} catch ( IllegalArgumentException e ) {
System.out.println( "Unexpected format of incoming date-time string: " + input + ". Exception: " + e ); // Handle exception for bad input.
}
Adjust to UTC for comparison.
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
Dump to console.
System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run.
dateTime: 2014-04-10T00:00:00.000-04:00
dateTimeUtc: 2014-04-10T04:00:00.000Z
† Wall-Time = The time as usually seen on some clock on some wall in some locality.
Regarding your first edit using the pattern "yyyy-MM-dd'T'HH:mm:ss.SSSZ" and experiencing a parse problem with Z-input, it is obviously a version problem, see here:
On Joda-Time-release-notes for change 1.6 to 2.0 =>
"Allow 'Z' and 'ZZ' in format patterns to parse 'Z' as '+00:00' [2827359]"
So the solution is to use the newest version of Joda-Time. Note that the use of the pattern symbol Z is more powerful than just to use a literal 'Z' in pattern expression because any ISO-8601-compatible string might not only contain "Z" at the end but also offsets like "+0200". And if the offset might contain a colon (example "+05:30") then you should use the double ZZ in your pattern.
Comment about your edit to remove the pattern symbol Z:
In that case I do not see any exception with version 2.1. Joda-Time will just interprete the input as local time in system timezone and add the appropriate timezone offset. Anyway, you have to adapt your pattern to expected inputs, not otherwise around.

How to set the TimeZone for String parsing in Android

I try to parse a String and set a time zone, but I can't produce the desired result.
String dtc = "2014-04-02T07:59:02.111Z";
SimpleDateFormat readDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date date = null;
try {
date = readDate.parse(dtc);
Log.d("myLog", "date "+date);
} catch (ParseException e) {
Log.d("myLog", "dateExcep " + e);
}
SimpleDateFormat writeDate = new SimpleDateFormat("dd.MM.yyyy, HH.mm");
writeDate.setTimeZone(TimeZone.getTimeZone("GMT+04:00"));
String dateString = writeDate.format(date);
At the output of the variable "dateString" still gives the time 07:59:02 , and I want to make it +4 hours in advance that is 11:59:02
You need to instruct the read-formatter to interprete the input as UTC (GMT - remember that Z stands for UTC in ISO-8601-format):
String dtc = "2014-04-02T07:59:02.111Z";
SimpleDateFormat readDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
readDate.setTimeZone(TimeZone.getTimeZone("GMT")); // missing line
Date date = readDate.parse(dtc);
SimpleDateFormat writeDate = new SimpleDateFormat("dd.MM.yyyy, HH.mm");
writeDate.setTimeZone(TimeZone.getTimeZone("GMT+04:00"));
String s = writeDate.format(date);
Then you will get:
02.04.2014, 11.59
Joda-Time
Doing date-time work much easier and simpler with the Joda-Time library than with the notoriously troublesome bundled java.util.Date & .Calendar classes.
Time Zone
Using proper time zone names, rather than a specific offset, is generally a wiser approach.
Example Code
Here is some example code using Joda-Time 2.3.
Notice:
Joda-Time has built-in parsers for strings in ISO 8601 format. No need to instantiate parsing or formatting objects.
Joda-Time is both parsing the UTC string and adjusting it to another time zone all in one call to the DateTime constructor.
When converting to a UTC-based dateTime in the last line, we still have the same moment in the timeline of the Universe (same count of milliseconds since Unix epoch).
Source…
String input = "2014-04-02T07:59:02.111Z";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Dubai" );
DateTime dateTimeDubai = new DateTime( input, timeZone ); (a) Parse, (b) Adjust time zone.
DateTime dateTimeUtc = dateTimeDubai.withZone( DateTimeZone.UTC );
Dump to console…
System.out.println( "input: " + input );
System.out.println( "dateTimeDubai: " + dateTimeDubai );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run…
input: 2014-04-02T07:59:02.111Z
dateTimeDubai: 2014-04-02T11:59:02.111+04:00
dateTimeUtc: 2014-04-02T07:59:02.111Z
you can take whatever pattern you want like i have date+ time zone. so you can set according to you. here is my code.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
here i have set the date format.
String currentDate = dateFormat.format(currentLocalTime);
String localTime = date.format(currentLocalTime);// to get the time zone i have used this.
String newtime=currentDate+localTime;// and then i have apeend this now print log you will get the desire result.

Convert Joda-Time DateTime - ISO 8601 format date to another date format

Inside my Java app I am using Joda-Time to convert the app user entered date from MM/dd/yyyy to ISO 8601 format in order to save it in DB.
Can someone please tell me how I can convert the ISO 8601 date back to MM/dd/yyyy format using Joda-Time?
My code convert user date to ISO 8601 date format:
String date1 = "05/05/2013";
DateTimeFormatter parser1 = DateTimeFormat.forPattern("MM/dd/yyyy");
DateTime dateTimeObj1 = DateTime.parse(date1,parser1);
DateTimeFormatter isoDateFormat = ISODateTimeFormat.dateTime();
String isoDateStr = isoDateFormat.print(dateTimeObj1);
System.out.println(isoDateStr);
Use Same Formatter
You use the same DateTimeFormatter object to parse as to print (render a string) in Joda-Time 2.3.
Time Zone
Note that your code neglected to address a time zone. In that case you get the JVM's default time zone. Not a good practice.
A DateTime represents both a date and a time. When parsing a string for only the date portion, the time portion is automatically set to first moment of the day. That first moment varies by time zone. So applying a different time zone gives a different result, a different point along the timeline of the Universe, a different milliseconds-since-epoch.
Note the call to withZone when defining the formatter.
Strings
Keep in mind that DateTime objects are not Strings. You can generate a string representation of the date-time information contained inside a DateTime by either:
Call the toString method on the DateTime instance.Every DateTime has a built-in ISO 8601 formatter, used automatically by the "toString" method.
Instantiate your own DateTimeFormatter instance.
Both of these string-generation techniques are seen in the example code below.
Example Code
// Usually better to specify a time zone than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Hong_Kong" );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy" ).withZone( timeZone );
// Parse string into a DateTime. Define the format.
String input = "05/05/2013";
DateTime dateTime = formatter.parseDateTime( input ); // Defaults to first moment of the day.
// Render date-time as an ISO 8601 string. The "toString" method on DateTime defaults to a built-in ISO 8601 formatter.
// A DateTime object is not itself a string. But a DateTime can generate a string by calling its "toString" method.
String iso8601String = dateTime.toString();
// Parse string into a DateTime. Passing to constructor conveniently uses the built-in ISO 8601 parser built into DateTime class.
DateTime dateTime2 = new DateTime( iso8601String, timeZone );
// Render date-time as a string in a particular format.
String output = formatter.print( dateTime2 );
Rather than hard-code a specific format, you can soft-code a localized format.
String outputUS = DateTimeFormat.forStyle( "S-" ).withLocale( Locale.US ).print( dateTime2 );
String outputQuébécois = DateTimeFormat.forStyle( "F-" ).withLocale( Locale.CANADA_FRENCH ).print( dateTime2 );
Dump to console…
System.out.println( "dateTime: " + dateTime ); // Implicit call to "toString" method in DateTime class generates a new string using a built-in formatter for ISO 8601 format.
System.out.println( "iso8601String: " + iso8601String );
System.out.println( "dateTime2: " + dateTime2 ); // Another implicit call to "toString" method on DateTime class. Generates a new string in ISO format.
System.out.println( "output: " + output );
When run…
dateTime: 2013-05-05T00:00:00.000+08:00
iso8601String: 2013-05-05T00:00:00.000+08:00
dateTime2: 2013-05-05T00:00:00.000+08:00
output: 05/05/2013
String Is Not a Date-Time
Do not think of date-time objects as strings.
A DateTime has no format. That class can parse a String in ISO 8601 format to instantiate a date-time object. Likewise a DateTimeFormatter can parse a String to instantiate a date-time object.
Going the opposite direction, a DateTime has a toString implementation that generates a String representation of the date-time object’s value. Likewise a DateTimeFormatter can generate a String representation of the date-time object’s value.
In all these cases the String representation is entirely different and separate from the date-time object.

Categories

Resources