Calendar.getTime() to Date object - java

I've an instance of a Calendar setted with UTC time zone, I need to be UTC becouse I've to sync with a server that is UTC.
I need to create a Date object from this Calendar, and I use Calendar.getTime().
But when I try to print out the Date object I see it with a different TimeZone (CEST instead of UTC)
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(timeMillisecond);
Date d = cal.getTime();
Log.d("TAG", d.toString());
EDIT:
When I pass the date object to the server, I get it with CEST timezone instead of UTC time zone.

You can use sdf, set its timezone and parse it accordingly.
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
try {
Date dt = sdf.parse(sdf.format(Calendar.getInstance()));
} catch (ParseException e) {
e.printStackTrace();
}
This worked for me.

Try the below code, it will provide you the date in UTC.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy dd,MM hh:mm:ss", Locale.getDefault());
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = dateFormat.format(new Date(timeMillisecond));
Log.d("TAG", utcTime);
It will provide you the date in yyyy dd,MM hh:mm:ss format but you can provide other format according to your need.

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()));

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));

How to convert date object to ones own timezone in android?

In android, I download date information from a MySQL database on a free web server, then convert it to a Date object using:
Note: the server time is 5 hours ahead of toronto.
public static Date getDateFromSQLDate(String sqldate) {
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = (Date) formatter.parse(sqldate);
TimeZone targetTimeZone = TimeZone.getDefault();
TimeZone serverTimeZone = TimeZone.getTimeZone("Europe/London");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.setTimeZone(serverTimeZone);
calendar.add(Calendar.MILLISECOND, serverTimeZone.getRawOffset() * -1);
if (serverTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, targetTimeZone.getRawOffset());
if (targetTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, targetTimeZone.getDSTSavings());
}
return calendar.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
This doesn't seem to work..
The problem is that the date is relative to the timezone of the server. The one downloading could be confused with the times as they don't know its not in their own timezone.
I have a Date object, is there a way I can retrieve the timezone of the location the users phone is in, and then modify that Date object to be their own timezone?
Thanks
EDIT:
How to get TimeZone from android mobile?
This gets a timezone object, but how do I change a Date object with it?
My app has to deal with server time similar to you.
(All datetime that I got from server represent datetime at UTC +00:00)
// date string to convert
String dateString = "2014-01-07 12:00:00"
// create date formatter, set time zone to UTC and parse
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
TimeZone serverTimeZone = TimeZone.getTimeZone("UTC");
formatter.setTimeZone(serverTimeZone);
Date date = formatter.parse(dateString);
Log.i("Debug", "date object : " + date.toString());
// I'm in Bangkok (UTC +07:00) so I'll see "Wed Jan 07 19:00:00 GMT+07:00 2015"
// If you do this in Toronto, you should see "Wed Jan 07 07:00:00 GMT -05:00 2015"
When you wanna print this date in Toronto, I believe you don't have to calculate DST by yourself because calendar and date formatter should handle that (not sure, I read from somewhere long ago)
// Create timezone for Toronto
TimeZone torontoTimeZone = TimeZone.getTimeZone("America/Toronto");
// Create calendar, set timezone, to see hour of day in Toronto
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(torontoTimeZone);
calendar.setTime(date);
Log.i("Debug", "Hour of day : " + calendar.get(Calendar.HOUR_OF_DAY);
// Hour of day : 7
// Create date formatter, set timezone, to print date for Toronto user.
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy, hh:mm", Locale.US);
formatter.setTimeZone(torontoTimeZone);
String torontoDate = formatter.format(date);
Log.i("Debug", "Date in Toronto : " + torontoDate);
// Date in Toronto : 07 Jan 2015, 07:00
You can set calendar and date formatter to user timezone by replace
TimeZone timezone = TimeZone.getTimeZone("America/Toronto")
with
TimeZone timezone = TimeZone.getDefault()
When I deal with date from server, I'll
request UTC time from server, if server doesn't send me UTC time, convert to UTC time first.
when parse date object from server, I always create date object represent time at UTC (time at server)
perform calculation or anything else with UTC date object.
pass only UTC date object from and to Activity/Fragment/Service/Model
only format date string with user timezone only when I need to display to user.
This is how you can change the date to your timezone
SimpleDateformat sdf = new SimpleDateFormat("yourformat");
TimeZone tz = TimeZone.getDefault();
sdf.setTimezone(tz);
sdf.format(yourdate); //will return a string in "your-format" to represent date
You're on the right track. You need to set the time zone of the Calendar object to the server's time zone. Then you can add the offset (and factor in DST) with the TimeZone that you got from the user's device (the link you included).
Code:
calendar.add(Calendar.MILLISECOND, serverTimeZone.getRawOffset() * -1);
if (serverTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, calendar.getTimeZone().getDSTSavings() * -1);
}
calendar.add(Calendar.MILLISECOND, targetTimeZone.getRawOffset());
if (targetTimeZone.inDaylightTime(calendar.getTime())) {
calendar.add(Calendar.MILLISECOND, targetTimeZone.getDSTSavings());
}
After that, you can retrieve the date in the usual way from the Calendar.
Also see this answer for more information.

Get the time of other TimeZone by date string, the result is wrong

I only have a date string, and I want to see the time in other TimeZone by it. So I did it like that:
String dateStr = "2014-05-15 16:14:58 PM";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("America/Denver"));
Date date = sdf.parse(dateStr);
System.out.println(date);
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
System.out.println(sdf1.format(date));
This is the current TimeZone in my computer:
The result that the code ran was that:
Fri May 16 06:14:58 CST 2014
2014-05-16 06:14:58 AM
The result is wrong, I had the right result by changing the TimeZone to "America/Denver" in my computer, and I saw that:
America/Denver —— 2014-05-15 02:14:58 AM
I don't know why it likes that?
But if I had a Date not a date String, I do that :
public static String getFormatedDateString(String _timeZone) {
TimeZone timeZone = null;
if (StringUtils.isEmpty(_timeZone)) {
timeZone = TimeZone.getDefault();
} else {
timeZone = TimeZone.getTimeZone(_timeZone);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf.setTimeZone(timeZone);
// TimeZone.setDefault(timeZone);
return sdf.format(new Date());
}
System.out.println("America/Denver —— " + getFormatedDateString("America/Denver"));
The result likes that:
------Asia/Shanghai------
2014-05-15 16:32:04 PM (current date)
America/Denver —— 2014-05-15 02:32:04 AM
This result is right.
So I was confused, I could't find the problem when I just have a date string and I want to know the time of other TimeZone. Could any body help me?
Date object in Java is independent of the concept of timezone.
What you want to do get the equivalent time in another timezone of a date string which is 'supposed' to be in your own timezone.
However, 2nd point appears backwards in your code:
String dateStr = "2014-05-15 16:14:58 PM";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("America/Denver"));
Date date = sdf.parse(dateStr);
What these 4 lines do is consider the date string as a point in time in "America/Denver" timezone.
When you parse it to the date object, it would give you the equivalent time in your own timezone.
You want it the other way round:
Hence staying close to your code (you can just use a single SimpleDateFormat instance effectively, which you can figure out later),
Drop the setTimezone on the first sdf:
String dateStr = "2014-05-15 16:14:58 PM";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
//sdf.setTimeZone(TimeZone.getTimeZone("America/Denver"));
Date date = sdf.parse(dateStr);
System.out.println(date);
Add the same setTimezone to the other sdf:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
sdf1.setTimeZone(TimeZone.getTimeZone("America/Denver"));
System.out.println(sdf1.format(date));
Now, you are parsing your date String to a date in your current (JVM's) timezone. Then format the same date to a different timezone's String.
Output I get with the changed code (my JVM's timezone being IST):
Thu May 15 16:14:58 IST 2014 // Parsed the date string in IST
2014-05-15 04:44:58 AM // Equivalent time in Denver

Java convert UTC timestamp to local DateTime

I know there are dozens of answered posts about converting UTC Time/Date To/From local time already but non helped me to figure out what my problem is.
My question is:
By having UTC timestamp, how can i get local DateTime?
This is what I have right now but this just convert the timestamp to DateTime format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getDefault());
sdf.format(new Date(timestamp * 1000));
Edited: I'm saving the UTC timestamp on the cloud so every device (Android/iOS) can query and convert to it's time zone.
Try this is working with me
public String getDateCurrentTimeZone(long timestamp) {
try{
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
return sdf.format(currenTimeZone);
}catch (Exception e) {
}
return "";
}
You can try this
String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss a z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateTimeString = sdf.format(new Date());
System.out.println(dateTimeString); // current UTC time
long timeStamp=sdf.parse(dateTimeString).getTime(); //current UTC time in milisec
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(timeStamp));
cal.add(Calendar.HOUR_OF_DAY, 5);
cal.add(Calendar.MINUTE, 30);
System.out.println(sdf.format(cal.getTime())); // time relevant to UTC+5.30
U can use Joda time to convert local to UTC and vice-versa
e.g Local to UTC
DateTime dateTimeNew = new DateTime(date.getTime(), DateTimeZone.forID("Asia/Calcutta"));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String datetimeString = dateTimeNew.toString("yyyy-MM-dd HH:mm:ss");
long milis = 0;
try {
milis = simpleDateFormat.parse(datetimeString).getTime();
} catch (ParseException e) {
e.printStackTrace();
}

Categories