Convert date with known timezone to UTC date - java

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

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

my Date Util formatter does not return my intended date format need help, [duplicate]

How to convert calendar date to yyyy-MM-dd format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.
A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date), Java uses Date.toString() to print the contents.
The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.time
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Joda-Time
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.
String myString=format1.format(date);
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
In order to parse a java.util.Date object you have to convert it to String first using your own format.
inActiveDate = format1.parse( format1.format(date) );
But I believe you are being redundant here.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));
This will display your date + 7 days in month, day and year format in a JOption window pane.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
My answer is for kotlin language.
You can use SimpleDateFormat to achieve the result:
val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)
for details click here.
OR
Use Calendar to do it for you:
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"
For more details check this answer.
I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).
Here is the one Liner:
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

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

Calendar.getTime() to Date object

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.

Android Date timezone issues

a). I have 3 strings representing the date, time and timeZone; ex.:
String date = "2012-09-04";
String time = "01:30:17";
String timeZone = "UTC";
and I want to create a date using these strings.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
Date createdDate = formatter.parse(date + " " + time + " " + timeZone);
doesn't work - I get the message "Unparseable date".
b). How can I get the Android device date in a specific timeZone?
I found just a way of converting current time to, for example, UTC timeZone:
Calendar cldr = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateInUTCTimeZone = sdf.format(cldr.getTime());
but I want the result to be a Date object.
The string "UTC" is nothing that the Date parser can recognize. If you need to use this constant for defining UTC, then the following date format should work for you
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss 'UTC'");
but I'd strongly recommend tu use the rfc3990 standard:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
and then represent your date as the following string (2012-09-04T13:24:59Z).
Finally if you want to represent a date which is in UTC to a certain time zone, use the following before formatting:
sdf.setTimeZone(TimeZone.getDefault()); //Choose the TimeZone you need

Categories