I have been searching over the net from past few hours to get the datetime in my system timezone.
When I use calendar.getTimezone.getDefaultName it always returns m
private String receivedFormat = "yyyy-MM-dd'T'HH:mm:ss", expectedFormat = "dd-MM-yyyy HH:mm:ss"; //Globall variables
//Write these three lines in your Test Class and below 2 methods
String dateString = "2018-08-14T07:00:00:00";
String returnString = correctDateFormat(dateString, receivedFormat, expectedFormat);
String result = getTimeInSelectedLocale(returnString);
Log.i("Ayaz", "Date: " +result);
/**
* @param receivedDate
* @param givenFormat
* @param expectedFormat
* @return returns date time in expected format
*/
public static String correctDateFormat(String receivedDate, String givenFormat, String expectedFormat) {
if (TextUtils.isEmpty(receivedDate)) {
return "";
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(givenFormat);
Date newDate = null;
try {
newDate = simpleDateFormat.parse(receivedDate);
} catch (ParseException e) {
e.printStackTrace();
}
simpleDateFormat = new SimpleDateFormat(expectedFormat);
receivedDate = simpleDateFormat.format(newDate);
return receivedDate;
}
/**
* @param dateString
* @return passed string date in different locale, My Db is in IST so I an converting IST in different locale
*/
public String getTimeInSelectedLocale(String dateString) {
if (TextUtils.isEmpty(dateString)) {
return dateString;
}
SimpleDateFormat sdf = new SimpleDateFormat(expectedFormat);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); //We want Indian time to change in different locale, so this line is compulsory, you can replace with your country
Date date1 = null;
try {
date1 = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
//below this line -> TimeZone.getTimeZone(TimeZone.getDefault().getID(), will return current locale for example for India "Asia/Kolkata" for UAE "Asia/Dubai"
sdf.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID())); //This line chooses current local in which you want time
String localDate = sdf.format(date1);
return localDate;
}
//I am converting the IST time "2018-08-14T07:00:00:00" into UAE(Duabai) "14-08-2018 05:30:00" and other countries