converting date object with a known timezone, to current timezone - java

So I'm getting some date objects from a web server, I know that the server has the time in GMT +1 (Berlin), how can I convert the date object, to the current phone timezone date object?
Most of the questions on stackoverflow are only about formatting within a timezone, but not actually converting like this.
I've tried this
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+1"));
calendar.setTime(timeFromServer);
Calendar calendar2 = new GregorianCalendar(TimeZone.getDefault());
calendar2.setTimeInMillis(calendar.getTimeInMillis());
WHen I print, calendar2.getTime().toString() and timeFromServer.toString() will be the same;

I used Joda time and it works. You can try with Joda time. This method will convert time from server to display format time below and change to the relevant local time
public static final String SERVER_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DISPLAY_POST_FORMAT = "HH:mm dd/MM/yyyy";
public static String convertDateStrToDisplayFormat(String timeFromServer) {
DateTimeFormatter serverFormatter = DateTimeFormat.forPattern(Constants.SERVER_FORMAT);
serverFormatter.withZone(DateTimeZone.forID("Europe/Berlin"));
DateTime dateTime = DateTime.parse(timeFromServer, serverFormatter);
DateTimeFormatter pointTimeFormatter = DateTimeFormat.forPattern(Constants.POINT_TIME_FORMAT);
pointTimeFormatter.withZone(DateTimeZone.forID("Europe/Berlin"));
return pointTimeFormatter.print(dateTime)
}

I use this to convert the date from the server and convert it to current phone timezone date object
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
sourceFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat deviceFormat = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",Locale.ENGLISH);
deviceFormat.setTimeZone(TimeZone.getDefault());
Date utcDate ;
Date deviceDate ;
utcDate = sourceFormat.parse(event_date);
deviceDate = deviceFormat.parse(utcDate.toString());
event_date is a String that has the server date. After this you have your converted Date on deviceDate.

java.util.Date does not use timezone, so when you try to print the string representation of the following date objects using method Date#toString(), the results are the same:
calendar2.getTime().toString()
timeFromServer.toString()
In order to test the string representation correctly with timezone, you need to use SimpleDateFormat:
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
f.setTimeZone(calendar.getTimeZone());
// Date correctly printed with timezone:
System.out.println(f.parse(calendar.getTime()));
However, your conversion written in the question is correct, here's how I tested it using JUnit:
#Test
public void testDateConversion() throws ParseException {
String serverText = "2017-03-02T11:54:30.207+01:00";
SimpleDateFormat serverFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
serverFmt.setTimeZone(TimeZone.getTimeZone("GMT+1"));
Date timeFromServer = serverFmt.parse(serverText);
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT-1"));
calendar.setTime(timeFromServer);
assertEquals(2017, calendar.get(Calendar.YEAR));
assertEquals(Calendar.MARCH, calendar.get(Calendar.MONTH));
assertEquals(2, calendar.get(Calendar.DAY_OF_MONTH));
assertEquals(9, calendar.get(Calendar.HOUR_OF_DAY));
assertEquals(54, calendar.get(Calendar.MINUTE));
assertEquals(30, calendar.get(Calendar.SECOND));
assertEquals(207, calendar.get(Calendar.MILLISECOND));
SimpleDateFormat currFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
currFmt.setTimeZone(calendar.getTimeZone());
System.out.printf("server_timestamp = %d, server_date = '%s', server_str = '%s'%n",
timeFromServer.getTime(),
serverFmt.format(timeFromServer),
timeFromServer.toString());
System.out.printf("current_timestamp = %d, current_date = '%s', current_str = '%s'%n",
calendar.getTime().getTime(),
currFmt.format(calendar.getTime()),
calendar.getTime().toString());
}
Result:
server_timestamp = 1488452070207, server_date = '2017-03-02T11:54:30.207+01:00', server_str = 'Thu Mar 02 11:54:30 CET 2017'
current_timestamp = 1488452070207, current_date = '2017-03-02T09:54:30.207-01:00', current_str = 'Thu Mar 02 11:54:30 CET 2017'
See also:
SimpleDateFormat (Java Platform SE 7)

Related

How to set String (HH:mm) to UTC time with current date and convert it to local time

I need to convert a string that is in (HH:mm) format which is supposed to be in UTC time to the local TimeZone. How to add the present date to the string and convert it local time.
I have tried using the calendar
String utcTimeString = "06:00";
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar now = Calendar.getInstance(Locale.getDefault());
now.setTime(sdf.parse(utcTimeString));
You are well advised to use the modern API for dates, times, time zones, offsets, calendars and more:
java.time
Doing so, it is pretty easy to
parse the time you receive
get the current date and
combine them to a date-time representation with a certain time zone
See this little example:
public static void main(String[] args) {
// create a time object from the String
LocalTime localTime = LocalTime.parse("06:00", DateTimeFormatter.ofPattern("HH:mm"));
// print it once in an ISO format
System.out.println(localTime.format(DateTimeFormatter.ISO_TIME));
// receive the date of today
LocalDate today = LocalDate.now();
// then use the date and the time object to create a zone-aware datetime object
ZonedDateTime zdt = LocalDateTime.of(today, localTime).atZone(ZoneId.of("UTC"));
// print it
System.out.println(zdt.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
The output is
06:00:00
2019-11-04T06:00:00Z[UTC]
Which you can format as desired using different DateTimeFormatters.
Try like the following.
public String getDateTimeInUTC(String yourTime){
Calendar cal = Calendar.getInstance();
SimpleDateFormat currentDate= new SimpleDateFormat("MMM dd, yyyy ");
String currentDateTime = currentDate.format(cal.getTime())+yourTime; // here concate your time with current date.
System.out.println("Current date with given time: "+currentDateTime);
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = df.parse(currentDateTime);
} catch (ParseException e) {
e.printStackTrace();
}
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
return formattedDate;
}
Call getDateTimeInUTC like below
String strTime = "12:10"; // your string time in HH:mm format
String finalDateTime = getDateTimeInUTC(strTime);
System.out.println("Final date-time in UTC: "+finalDateTime);
OUTPUT:
Current date with given time: Nov 04, 2019 12:10
Final date-time in UTC: Nov 04, 2019 18:10
You can Check this Out :
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
//change the format according to your need
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));
//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));

How change String to Date format

I have this string: 2018-09-22 10:17:24.772000
I want to convert it to Date:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
String sdate = "2018-09-22 10:17:24.772000";
Date dateFrom = simpleDateFormat.parse(sdate);
but it shows: Sat Sep 22 10:17:24 GMT+03:30 2018
Here is what you should do instead, you are printing date object itself, you should print its format.
I will provide the code with old date api and new local date api :
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
String sdate = "2018-09-22 10:17:24.772000";
Date dateFrom = simpleDateFormat.parse(sdate);
System.out.println(dateFrom); // this is what you do
System.out.println(simpleDateFormat.format(dateFrom)); // this is what you should do
// below is from new java.time package
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
System.out.println(LocalDateTime.parse(sdate, formatter).format(formatter));
output is :
Sat Sep 22 10:30:16 EET 2018
2018-09-22 10:30:16.000000
2018-09-22 10:17:24.772000
Hope This will help you
public class Utils {
public static void main(String[] args) {
String mytime="2018-09-22 10:17:24.772000";
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSSSSS");
Date myDate = null;
try {
myDate = dateFormat.parse(mytime);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd");
String finalDate = timeFormat.format(myDate);
System.out.println(finalDate);
}
}
Looks to me like you have converted it to a Date. What is your desired result? I suspect what you are wanting to do is to create another Simple date format that shows your expected format and then use simpledateformat2.format(dateFrom)
I should also point out based on past experience that you should add a Locale to your simple date formats otherwise a device with a different language setting may not be able to execute this code
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS", Locale.US);

How to Convert Time Zone to UTC time zone using jorda time

Using this code
String twelveHourTime="06:00 PM";
public static DateTime convert12HourTimeTo24HourTime(String twelveHourTime) {
DateTimeFormatter dateTimeFormatter =
DateTimeFormat.forPattern(AppConstants.TWELVE_HOUR_TIME_FORMAT);
DateTime dateTime = dateTimeFormatter.parseDateTime(twelveHourTime);
return new DateTime().withHourOfDay(dateTime.getHourOfDay())
.withMinuteOfHour(dateTime.getMinuteOfHour());
}
I am getting this date time:
String datetime=2017-09-15T18:00:23.153+05:30
Now I want to convert it to the US time zone.
Please suggest me how to do this.
You can use SimpleDateFormat for conversion
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH24:MI");
Date date = df.parse(datetime);
Use localDateTime:
DateTime dt = new LocalDateTime(timestamp.getTime()).toDateTime(DateTimeZone.UTC);
you can use it by using TimeZone and SimpleDateFormat :-
TimeZone time = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(time);
final Date startDate = cal.getTime();
SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-M-yyyy hh:mm:ss a");
sdfAmerica.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String sDateInAmerica = sdfAmerica.format(startDate);
edDate.setText(sDateInAmerica);

Convert date with known timezone to UTC date

Date and Time Conversion has always been my weak link. I have the following values in string format:
String date="2015-08-21 03:15" and timezone for this date is
String timeZone="GMT+05:30";
Now I need to covert this date, for which I already know the timezone, to UTC date.
If you are given time in "GMT+05:30" timezone next code will convert it to UTC timezone:
String strDate = "2015-08-21 03:15";
String timeZone="GMT+05:30";
String format = "yyyy-MM-dd HH:mmz";
SimpleDateFormat formatter = new SimpleDateFormat(format);
Date dateStr = formatter.parse(strDate+timeZone);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = formatter.format(dateStr);
System.out.println("UTC datetime is: "+formattedDate);
You can try like this:
Approach 1: Using Java Date:
//Your input date string
String date="2015-08-21 03:15";
// date format your string
String format = "yyyy-MM-dd HH:mm";
//Create SimpleDateFormat instance
SimpleDateFormat sdf = new SimpleDateFormat(format);
// Convert Local Time to UTC
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//parse your input date string to UTC date
Date gmtTime = new Date(sdf.parse(date));
Approach 2: Using Joda time (recommended)
String dateString = "2015-08-21 03:15:00+5:30";
String pattern = "yyyy-MM-dd HH:mm:ssZ";
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
DateTime dateTime = dtf.parseDateTime(dateString);
System.out.println(dateTime);
Since you only want a Java-8-solution:
String input = "2015-08-21 03:15";
String offsetInfo = "GMT+05:30";
LocalDateTime ldt =
LocalDateTime.parse(input, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm"));
ZoneOffset offset =
ZoneOffset.of(offsetInfo.substring(3)); // GMT-prefix needs to be filtered out
LocalDateTime result =
ldt.atOffset(offset).withOffsetSameInstant(ZoneOffset.UTC).toLocalDateTime();
System.out.print(result); // output: 2015-08-20T21:45
A Date in java represents the number of milliseconds since 1970. This number alone has no specific time zone. This means if you create a Date with new Date() you get the current milliseconds since 1970 and if you call toString on it this value gets represented in your current locale timezone. The actual time this number represents is time zone specific. This is the reason why you can set a TimeZone on Calendar and Format classes.
To instantiate a calendar with a specific TimeZone you can do this:
public static Calendar getUtcCalendar() {
GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
}
So to convert a Date to a specific time in UTC TimeZone:
Calendar calendar = getUtcCalendar();
calendar.setTime(date);
return calendar;
You can see:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
Date date = null;
try {
//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
date = sdf.parse(review);
} catch (ParseException e) {
e.printStackTrace();
}
//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
System.out.println(sdf.format(date));

Convert UTC into Local Time on Android

In my project, I have get the API response in json format. I get a string value of time in UTC time format like this Jul 16, 2013 12:08:59 AM.
I need to change this into Local time.
That is where ever we use this the app needs to show the local time. How to I do this?
Here is some Code I have tried:
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(aDate);
Assume aDate contains Jul 16, 2013 12:08:59 AM
Here's my attempt:
String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
Also notice the "a" for the am/pm marker...
I should like to contribute the modern answer. While SimpleDateFormat was the class we had for parsing and formatting date-times in 2013 (apart from Joda-Time), it is now long outdated, and we have so much better in java.time or JSR-310, the modern Java date and time API that came out with Java 8 in 2014.
But most Android devices still don’t run Java 8, I hear you say. Fortunately you can still use the modern Java date and time API on them through the ThreeTenABP, the backport of JSR-310 to Android Java 7. Details are in this question: How to use ThreeTenABP in Android Project.
Now the code is:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MMM dd, uuuu hh:mm:ss a", Locale.ENGLISH);
String aDate = "Jul 16, 2013 12:08:59 AM";
String formattedDate = LocalDateTime.parse(aDate, formatter)
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(ZoneId.systemDefault())
.format(formatter);
System.out.println(formattedDate);
Since my computer is running Europe/Copenhagen time zone, which in July is 2 hours ahead of UTC, this prints
Jul 16, 2013 02:08:59 AM
Further points:
Since you have AM in your string, I assumed your hours are within AM, from 1 through 12. To parse and format them correctly you need lowercase h in the format pattern string. Uppercase H is for hour-of-day from 0 through 23.
Prefer to give an explcit locale to the formatter (whether SimpleDateFormat or DateTimeFormatter). If no locale is given, the formatter will use the device’s default locale. “Jul” and “AM” are in English, and your code may run nicely on many devices until one day it runs on a device with non-English locale and crashes, and you have a hard time figuring out why.
If you can, give the desired time zone explictly, for example as ZoneId.of("Asia/Kolkata"). The JVM’s default time zone may be changed by other parts of your program or other programs running in the same JVM, so is not reliable.
1.Local to UTC Converter
public static String localToUTC(String dateFormat, String datesToConvert) {
String dateToReturn = datesToConvert;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getDefault());
Date gmt = null;
SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFormat);
sdfOutPutToSend.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
gmt = sdf.parse(datesToConvert);
dateToReturn = sdfOutPutToSend.format(gmt);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}
2. UTC to Local Converter
public static String uTCToLocal(String dateFormatInPut, String dateFomratOutPut, String datesToConvert) {
String dateToReturn = datesToConvert;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormatInPut);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmt = null;
SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFomratOutPut);
sdfOutPutToSend.setTimeZone(TimeZone.getDefault());
try {
gmt = sdf.parse(datesToConvert);
dateToReturn = sdfOutPutToSend.format(gmt);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn; }
//your UTC time var
long time = UTCtime;
//convert it
Time timeFormat = new Time();
timeFormat.set(time+TimeZone.getDefault().getOffset(time));
//use the value
long localTime = timeFormat.toMillis(true);
Use the following code.
TimeZone defaultTimeZone = TimeZone.getDefault();
String strDefaultTimeZone = defaultTimeZone.getDisplayName(false, TimeZone.SHORT);
//The code you use
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(strDefaultTimeZone));
String formattedDate = simpleDateFormat.format(aDate);
This should work.
This is how i do it on android Build.VERSION.SDK_INT < 26
int offset = TimeZone.getDefault().getRawOffset();
String str_date='20:30 12-01-2021';
DateFormat formatter = new SimpleDateFormat("HH:mm dd-MM-yyy",Locale.US);
Date date = formatter.parse(str_date);
long utcTime = date.getTime() + (3600000*3);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy", Locale.US);
String dateStr = sdf.format(utcTime + offset);
System.out.println(dateStr);
As my server sends the time with -3 timezone i have to add (3600*3) to getTime and i save it into utcTime, this way utcTime is in UTC. And then i add to utcTime the offset of the phone current timezone.
In my case as my timezone is -3 its prints:
20:30 12/01/2021
But if i change my time zone the date also changes.
Use this code:
public static String stringDateWithTimezone(Date date, String pattern, TimeZone timeZone) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.US);
if (timeZone != null) {
simpleDateFormat.setTimeZone(timeZone);
}
return simpleDateFormat.format(date);
} catch (Exception e) {
Timber.e(e);
return null;
}
}
call in another class:
String dateUtc = DateUtil.stringDateWithTimezone(new Date(), "yyyy-MM-dd hh:mm:ss", TimeZone.getTimeZone("UTC"));

Categories