Convert Local time to UTC and vice versa
Try this:
//convert to UTC to Local format
public Date getUTCToLocalDate(String date) {
Date inputDate = new Date();
if (date != null && !date.isEmpty()) {
@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
inputDate = simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
return inputDate;
}
//convert Local Date to UTC
public String getLocalToUTCDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
Date time = calendar.getTime();
@SuppressLint("SimpleDateFormat") SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
return outputFmt.format(time);
}
I converted local time to GMT/UTC and vice versa using these two methods and this works fine without any problem for me.
public static Date localToGMT() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmt = new Date(sdf.format(date));
return gmt;
}
pass the GMT/UTC date which you want to convert into device local time to this method:
public static Date gmttoLocalDate(Date date) {
String timeZone = Calendar.getInstance().getTimeZone().getID();
Date local = new Date(date.getTime() + TimeZone.getTimeZone(timeZone).getOffset(date.getTime()));
return local
}
A simplified and condensed version of the accepted answer:
public static Date dateFromUTC(Date date){
return new Date(date.getTime() + Calendar.getInstance().getTimeZone().getOffset(new Date().getTime()));
}
public static Date dateToUTC(Date date){
return new Date(date.getTime() - Calendar.getInstance().getTimeZone().getOffset(date.getTime()));
}