I need to format the date into a specific string.
I used SimpleDateFormat
class to format the date using the pattern \"yyyy-MM-dd\'T\'HH:m
What you can do is just add the ":" manually using substring(). I have faced this earlier and this solution works.
You can use Joda Time instead. Its DateTimeFormat
has a ZZ
format attribute which does what you want.
Link
Big advantage: unlike SimpleDateFormat
, DateTimeFormatter
is thread safe. Usage:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ")
.withLocale(Locale.ENGLISH);
Simply refactor this code and replace the 'Locale.getDefault()' with the Locale you need
private SimpleDateFormat getDateFormat() {
SimpleDateFormat dateFormat = (SimpleDateFormat) SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.DEFAULT, Locale.getDefault());
String pattern = dateFormat.toLocalizedPattern();
pattern = pattern.trim();
dateFormat.applyLocalizedPattern(pattern);
return dateFormat;
}
//And here is the usage
SimpleDateFormat sdf = getDateFormat();
sdf.format(new Date());
Why not just do it manually with regexp?
String oldDate = "2013-01-04T15:51:45+0530";
String newDate = oldDate.replaceAll("(\\+\\d\\d)(\\d\\d)", "$1:$2");
Same result, with substring (if performance is an issue).
String oldDate = "2013-01-04T15:51:45+0530";
int length = oldDate.length();
String newDate = oldDate.substring(0, length - 2) + ':' + oldDate.substring(length - 2);
If you want the date for a different timeZone (which the title suggests)
val nowMillsUTC = System.currentTimeMillis()
val timeZoneID = "Australia/Perth"
val tz = TimeZone.getTimeZone(timeZoneID)
val simpleDateFormat = SimpleDateFormat("HH.mm dd.MMM.yyyy", Locale.getDefault())
simpleDateFormat.setTimeZone(tz)
val resultTxt = simpleDateFormat.format(nowMillsUTC)
print(timeZoneID + " -> " + resultTxt)
// Australia/Perth -> 19.59 21.Mar.2019
You can also use "ZZZZZ" instead of "Z" in your pattern (according to documentation). Something like this
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ", Locale.ENGLISH);
Log.e(C.TAG, "formatted string: "+sdf.format(c.getTime()));