Converting UTC date from server into local time - java

I am getting this string as Date from Server
2016-06-11T11:14:57.000Z
Since it is UTC, I want to convert to my local time.
SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat endFormat = new SimpleDateFormat("hh:mm a");
mFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));
Date date = mFormat.parse(mBooking.startTime);
However the date converted to 2:00AM
Now i don't get it why 11am is getting converted to 2:00AM
What wrong am i doing?

Because you don't set the timezone properly to each SimpleDateFormat indeed mFormat should be set to UTC and endFormat to GMT + 5, here is what you are supposed to do:
SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// Set UTC to my original date format as it is my input TimeZone
mFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = mFormat.parse("2016-06-11T11:14:57.000Z");
SimpleDateFormat endFormat = new SimpleDateFormat("hh:mm a");
// Set GMT + 5 to my target date format as it is my output TimeZone
endFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));
System.out.println(endFormat.format(date));
Output:
04:14 PM

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

Simpledateformat parse subtracts instead of adding

I'm trying to change the time that I get (in CEST/CET) to GMT to store it in my database. BUT when I parse the date in CEST to GMT, instead of subtracting 2, it adds 2 hours!
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); //My locale is CEST
Date dateOfBooking = formatter.parse(bookedDate + " " + bookedDateTime); //Here the time is 10:09
formatter.setTimeZone(TimeZone.getTimeZone("GMT")); // Timezone I need to store the date in
dateOfBooking = formatter.parse(bookedDate + " " + bookedDateTime); // Here the time is 12:09
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
bookedDateTime = timeFormat.format(dateOfBooking);
Can anybody explain why? I've tried setting my local timezone to different ones and it always work the other way, subtracting instead of adding and viceversa.
You are parsing the date again as GMT. (which, when printed as CEST, or your locale timezone, will add + 2 hours)
What you actually want is to print out the already parsed date as GMT:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); //My locale is CEST
Date dateOfBooking = formatter.parse(bookedDate + " " + bookedDateTime); //Here the time is 10:09
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
bookedDateTime = timeFormat.format(dateOfBooking);
System.out.println(bookedDateTime);
Basicly you have to set the GMT zone in your timeFormat that you use to create the time string, not the formatter that you use for parsing

How to get time with GMT like 2016-02-28/20:31 GMT

I want time with GMT string too.
But Im not able to get it.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd/hh-mm");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = new Date();
System.out.println("date "+dateFormat.format(date));
But Im getting like this 2015-12-28/11-53
without GMT at the end
Use
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd/hh-mm z");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
instead of
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd/hh-mm");
where 'z' means timezone

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

Issue i am facing with dateFormat.parse(string)?

I have below code snippet
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");
String processedContentDate="2012-04-10 12:53:28.033";
java.util.Date parsedDate = dateFormat.parse(processedContentDate);
java.sql.Timestamp timestamp = new java.sql.Timestamp(
parsedDate.getTime());
I get parsed date as Tue Apr 10 00:53:28 IST 2012 and timestamp as 2012-04-10 00:53:28.033 . i want to get the time exactly as 12:53:28.033(as in my original string)
not 00:53:28.033. Not getting why 12:53:28 is getting converted to 00:53:28. what should I do to get 12:53:28?
EDIT: After getting the response, I tried this small programme where current time is 14:34:38.899
but at both lines i.e at line 1 and line 2, I got below parsed date
2012-04-10 14:34:38.899
As per reply I should have got 02:34:38.899 at line 1 as date format is yyyy-MM-dd hh:mm:ss.SSS")
java.util.Date date= new java.util.Date();
String strDate=date.toString();
java.util.Date parsedDate;
java.util.Date parsedDate2;
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss.SSS");// line 1
SimpleDateFormat dateFormat2 = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS");//line 2
try {
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
strDate=timestamp.toString();
parsedDate = dateFormat.parse(strDate);//line1
parsedDate2 = dateFormat2.parse(strDate);//line2
Define your dateFormat like that
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
HH instead of hh. See SimpleDateFormat
Your date format must be yyyy-MM-dd HH:mm:ss.SSS.
hh is hours in am/pm, while HH is hours in a day (that's where you mistake is). See SimpleDateFormat.
As per definition of Date.toString() and Timestamp.toString, the .toString() output is always using a 24-hour clock. If you want to show the time using AM/PM, you should use the dateformatter to print the date. As you are using the same date/time as a source for both (strDate will use 14:34), when you parse the date, the SimpleDateFormat using the 12-hour clock is "lenient" and allows parsing of 14 as an hour.
If you set
dateFormat.setLenient(false);
you'll probably find that the dateFormat.parse(strDate) will fail.
To print dates, I would never rely on toString, but always use a formatter.
System.out.println(dateFormat.format(parsedDate)); // should show ...02:36...
System.out.println(dateFormat2.format(parsedDate)); // should show ...14:36...
System.out.println(dateFormat.format(parsedDate2)); // should show ...02:36...
System.out.println(dateFormat2.format(parsedDate2)); // should show ...14:36...
Try below code:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = fmt.parse("yourdate");
SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy hh:mm a");String myDate = fmtOut.format(date);
If yourdate is 2016-06-10 12:06:43, then output will be 10-06-2016 12:06 pm.

Categories