Calling
DateTime.now().format()
results in ’28/08/2012 16:20′ for current user locale ‘French (France)’ & ‘8/28/2012 4:20 PM’ for current user locale ‘English (United States)’.Calling
DateTime.now().date().format()
results in ’28/08/2012′ for current user locale ‘French (France)’ &8/28/2012
for current user locale ‘English (United States)’.Ideally a
Time.format()
instance method would exist so thatDateTime.now().time().format()
results in ’16:20′ for current user locale ‘French (France)’ & ‘4:20 PM’ for current user locale ‘English (United States)’.Please suggest any and all locale sensitive workarounds for formatting the Time part only.
In my particular case, I’m not displaying this Time part only to the user via Visualforce, so an Apex workaround is what I’m looking for.
Answer
You could just split the DateTime format() result on the first space – does that give you what you’re looking for?
public String myDateFormat(DateTime dt) {
String[] parts = dt.format().split(' ');
return (parts.size() == 3) ? (parts[1] + ' ' + parts[2]) : parts[1];
}
produces
6:38 PM
for me in English (United States), and
18:42
in French(France).
UPDATE
As tomlogic points out, the above method is not very robust – some locales may include spaces in the date or time portion of the format, and the ordering is not consistent. This second attempt assumes that the date and time are separated by zero or more spaces, but handles spaces within the two portions, and either ordering of date and time. The only assumption made is that the formatted Date is contained within the formatted Time:
public String myDateFormat(DateTime dt) {
return dt.format().replace(dt.date().format(), '').trim();
}
Seems to work fine for Hebrew, Vietnamese & Korean, as well as English and French.
Attribution
Source : Link , Question Author : mjgallag , Answer Author : Community