there is a form having a drop down for country ,user will select the country ,then there is a drop down for time zone ,user will select the time zone which are available in country selected by the user.Then user will enter the local date( eg: 26-Dec-2014) and time( 23:11)(24 hours time) this entered date and time is for the selected country and time zone.
now i have to convert this date and time to GMT time zone. how can i do this using joda time
how the daylight saving time(DST) will be calculate?
i have made a function which accepts the parameters as from time zone,to time zone,date
public static String convertTimeZones( String fromTimeZoneString,
String toTimeZoneString, String fromDateTime) {
DateTimeZone fromTimeZone = DateTimeZone.forID(fromTimeZoneString);
DateTimeZone toTimeZone = DateTimeZone.forID(toTimeZoneString);
DateTime dateTime = new DateTime(fromDateTime, fromTimeZone);
DateTimeFormatter outputFormatter
= DateTimeFormat.forPattern("dd-MMM-yyyy HH:mm").withZone(toTimeZone);
return outputFormatter.print(dateTime);
}
i want to pass the date to this function in a format (24-Feb-2014 12:34) but it is not taking this format
//so we can get the local date
//UTC = true, translate from UTC time to local
//UTC = false, translate from local to UTC
public static String formatUTCToLocalAndBackTime(String datetime, boolean UTC) {
String returnTimeDate = "";
DateTime dtUTC = null;
DateTimeZone timezone = DateTimeZone.getDefault();
DateTimeFormatter formatDT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dateDateTime1 = formatDT.parseDateTime(datetime);
DateTime now = new DateTime();
DateTime nowUTC = new LocalDateTime(now).toDateTime(DateTimeZone.UTC);
long instant = now.getMillis();
long instantUTC = nowUTC.getMillis();
long offset = instantUTC - instant;
if (UTC) {
//convert to local time
dtUTC = dateDateTime1.withZoneRetainFields(DateTimeZone.UTC);
//dtUTC = dateDateTime1.toDateTime(timezone);
dtUTC = dtUTC.plusMillis((int) offset);
} else {
//convert to UTC time
dtUTC = dateDateTime1.withZoneRetainFields(timezone);
dtUTC = dtUTC.minusMillis((int) offset);
}
returnTimeDate = dtUTC.toString(formatDT);
return returnTimeDate;
}
Java time api is better compared to joda time api when it comes to various timezones, specially with day light savings
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
LocalDateTime start = LocalDateTime.of(2021, 02, 25, 14, 25, 00);
ZoneId zone = ZoneId.of("Asia/Singapore");
start = start.atZone(zone).withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
Related
This question already has answers here:
TimeZone problem in Java
(3 answers)
GregorianCalendar Class in Java
(3 answers)
Calendar returns date in wrong time zone
(5 answers)
Closed 2 years ago.
I have to use the date time which I receive by user, and convert that time to UTC from the given time. Right now, all the solutions are working, but not as I needed. First, it converts to the time zone, but I don't want to initially convert. I have to set that timezone on my date and then convert that time to UTC. Right now, each and every solution shows that I have to pass date and time, and then I am getting updated date and time with the time zone which I provide, and then converts to the UTC. This was not my question.
My user will send me date time of any timezone, and my server will be running on UTC time zone. I will get the zone id from the front end. I want to convert that date time to UTC and verify with my other conditions. It might be possible that I will get UTC-7 time in one request, and then after in next request I will get UTC+5:30. So, all the time should be converted to the UTC and I am not able to set timezone on date.
I wanted to set the specific timezone to date, and I am getting the date and time of that timezone, but I'm not able to set the exact timezone. Here, I am adding my code please tell me where I am wrong:
Calendar laCalendar = Calendar.getInstance();
laCalendar.set(2020, 8, 14, 00, 00);
Date losAngelesDate = laCalendar.getTime();
System.out.println("LA Date1===>" + losAngelesDate);
SimpleDateFormat simpleTimeFormatForUSA = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
simpleTimeFormatForUSA.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
String americaDateString = simpleTimeFormatForUSA.format(laCalendar.getTime());
SimpleDateFormat dateFormatUSA = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
losAngelesDate = dateFormatUSA.parse(americaDateString);
System.out.println("LA Date2===>" + losAngelesDate);
Date utcDate = losAngelesDate;
Calendar calendar = Calendar.getInstance();
calendar.setTime(utcDate);
TimeZone timeZone = TimeZone.getTimeZone("UTC");
SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
simpleTimeFormat.setTimeZone(timeZone);
String utcTime = simpleTimeFormat.format(calendar.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
utcDate = dateFormat.parse(utcTime);
System.out.println("UTC date====>" + utcDate);
And my output is
LA Date1===>Mon Sep 14 00:00:56 UTC 2020
LA Date2===>Sun Sep 13 17:00:00 UTC 2020
UTC date====>Sun Sep 13 17:00:00 UTC 2020
Here you can see that my DateTime is converted, but time zone is still UTC and I wanted to update that.
Here, is how I would write it using Java 8 Date/Time APIs.
public static void main(String[] args)
{
System.out.println("UTC");
toTimeZone(new Date(), TimeZone.getTimeZone(ZoneId.of("UTC")));
System.out.println("America/Los_Angeles");
toTimeZone(new Date(), TimeZone.getTimeZone(ZoneId.of("America/Los_Angeles")));
}
public static void toTimeZone(Date date, TimeZone timeZone)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Instant epochMillisInstant = Instant.ofEpochMilli(calendar.getTimeInMillis());
LocalDateTime localDateTime = LocalDateTime.ofInstant(epochMillisInstant, ZoneId.systemDefault());
ZonedDateTime dateTimeToConvert = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
ZonedDateTime dateTimeWithTimeZone = dateTimeToConvert.withZoneSameInstant(timeZone.toZoneId());
String formattedDateForNewTimeZone = dateTimeWithTimeZone.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"));
System.out.println(formattedDateForNewTimeZone);
}
Using Just Java 8 Date/Time APIs - Shorter Version
public static void main(String[] args) {
System.out.println("UTC");
toTimeZone(LocalDateTime.now(),"UTC");
System.out.println("America/Los_Angeles");
toTimeZone(LocalDateTime.now(),"America/Los_Angeles");
}
private static void toTimeZone(LocalDateTime localDateTime, String timeZone) {
ZonedDateTime localDateTimeToConvert = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
ZonedDateTime zonedDateTime = localDateTimeToConvert.withZoneSameInstant(ZoneId.of(timeZone));
String formattedDateForNewTimeZone = zonedDateTime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"));
System.out.println(formattedDateForNewTimeZone);
}
Before you convert the Calendar to a Date, set the Timezone to your preference.
For example:
import java.util.Calendar;
import java.util.TimeZone;
public class Timezone{
public static void main(String []args){
Calendar laCalendar = Calendar.getInstance();
TimeZone timezone = TimeZone.getTimeZone("UTC");
laCalendar.set(2020, 8, 14, 00, 00);
laCalendar.setTimeZone(timezone);
java.util.Date losAngelesDate = laCalendar.getTime();
System.out.println(losAngelesDate.toString());
}
}
I was trying to convert input date time to GMT+0 , later convert that back to its local time. Though local to GMT+0 conversion works, the later conversion-gmt to local fails!
Calendar cal=Calendar.getInstance();
cal.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println("my inputTime:"+ sdf.format(cal.getTime()));
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("gmt+0 converted time:"+ sdf.format(cal.getTime()));
//now i want to get my local time from this converted gmt+0 standard time
String standdardTimeStr=sdf.format(cal.getTime());
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date=sdf2.parse(standdardTimeStr);
Calendar cal2= Calendar.getInstance();
cal2.setTime(date);
System.out.println("standard input time:"+ sdf2.format(cal2.getTime()));
sdf2.setTimeZone(TimeZone.getTimeZone("GMT+6")); //or Asia/Dhaka
System.out.println("gmt+6 convertedtime:"+ sdf2.format(cal2.getTime()));
And this is my output:
my inputTime:2020-07-13T15:02:16.849
gmt+0 converted time:2020-07-13T09:02:16.849
standard input time:2020-07-13T09:02:16.849 //taking upper line as input-gmt+0
gmt+6 convertedtime:2020-07-13T09:02:16.849 //this date was supposed to be same as the first date
Please point out what am I doing wrong in coding or conceptually?
Just for the case you want a solution with a modern API, see this commented example:
public static void main(String[] args) {
// provide some fix example datetime String
String dateTime = "2020-05-08T13:57:06.345";
// create the two time zones needed before
ZoneId utc = ZoneId.of("UTC"); // UTC = GMT (+0)
ZoneId local = ZoneId.systemDefault(); // the zone of your JVM / system
/*
* then parse the String which doesn't contain information about a zone
* to an object that just knows date and time
*/
LocalDateTime ldt = LocalDateTime.parse(dateTime);
// and use that to create a zone-aware object with the same date and time
ZonedDateTime utcZdt = ZonedDateTime.of(ldt, utc);
// finally adjust its date and time by changing the zone
ZonedDateTime localZdt = utcZdt.withZoneSameInstant(local);
// then print both results
System.out.println(utcZdt + "\t==\t" + localZdt);
// and maybe try to use a different output format by defining a custom formatter
DateTimeFormatter gmtStyleDtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSO");
System.out.println(utcZdt.format(gmtStyleDtf)
+ "\t==\t" + localZdt.format(gmtStyleDtf));
}
which ouputs the following lines on my system (might be different on yours due to different time zones):
2020-05-08T13:57:06.345Z[UTC] == 2020-05-08T15:57:06.345+02:00[Europe/Berlin]
2020-05-08T13:57:06.345GMT == 2020-05-08T15:57:06.345GMT+2
EDIT:
Here's a possibility of doing the same thing but just dealing with offsets instead of time zones:
public static void main(String[] args) {
// provide some fix example datetime String
String dateTime = "2020-05-08T13:57:06.345";
// create the two offsets needed
ZoneOffset gmt = ZoneOffset.ofHours(0); // UTC = GMT (+0)
ZoneOffset gmtPlusSix = ZoneOffset.ofHours(6); // Asia/Dhaka ;-)
/*
* then parse the String which doesn't contain information about a zone
* to an object that just knows date and time
* NOTE: this just parses the String and does nothing else
*/
LocalDateTime justDateAndTime = LocalDateTime.parse(dateTime);
// and use that to create an offset-aware object with the same date and time
OffsetDateTime dateAndTimeAndGmtPlusSix = OffsetDateTime.of(justDateAndTime, gmtPlusSix);
// finally adjust its date and time by changing the offset keeping the instant
OffsetDateTime dateAndTimeInGmt = dateAndTimeAndGmtPlusSix.withOffsetSameInstant(gmt);
// then print both results
System.out.println(dateAndTimeAndGmtPlusSix + "\t==\t" + dateAndTimeInGmt);
// and maybe try to use a different output format by defining a custom formatter
DateTimeFormatter gmtStyleDtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSO");
System.out.println(dateAndTimeAndGmtPlusSix.format(gmtStyleDtf)
+ "\t==\t" + dateAndTimeInGmt.format(gmtStyleDtf));
}
Output:
2020-05-08T13:57:06.345+06:00 == 2020-05-08T07:57:06.345Z
2020-05-08T13:57:06.345GMT+6 == 2020-05-08T07:57:06.345GMT
Note that a Z is equivalent to an offset of GMT/UTC +0.
This way, you could create a method like
public static String convert(String datetime, int fromOffset, int toOffset) {
ZoneOffset fromZoneOffset = ZoneOffset.ofHours(fromOffset);
ZoneOffset toZoneOffset = ZoneOffset.ofHours(toOffset);
OffsetDateTime odt = LocalDateTime.parse(datetime).atOffset(fromZoneOffset);
return odt.withOffsetSameInstant(toZoneOffset)
.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
maybe handle invalid argument values, use it like this
public static void main(String[] args) {
String dateTime = "2020-05-08T13:57:06.345";
System.out.println(convert(dateTime, 6, 0)));
}
and receive the output
2020-05-08T07:57:06.345
I don't know why you're using a Calendar object. Javadoc of Calendar.getInstance() says:
The Calendar returned is based on the current time in the default time zone
Which means that calling cal.setTime(new Date()); is entirely redundant.
But, even worse than that, the following three are all the same:
// The very long way
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
Date date = cal.getTime();
// The long way
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
// The simple way
Date date = new Date();
A Date object always stores the date/time in UTC (GMT+0). Time zones are applied when a string is parsed, and when a string is formatted.
Parsing a string that doesn't specify a time zone offset will be parsed in the time zone of the SimpleDateFormat, which is the default time zone (aka the "local" time zone) unless otherwise specified, and the parsed value is converted to UTC for storage in a Date object.
Formatting a Date value to string will always use the time zone of the SimpleDateFormat.
Cleaning up the code in the question to not use Calendar, since that just obfuscates the issue, and commenting it to show what is going on, will answer your question of "point out what am I doing wrong in coding or conceptually":
Date now = new Date();
// Format the date in the local time zone
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println("my inputTime:"+ sdf.format(now));
// Format the date in GMT time zone
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("gmt+0 converted time:"+ sdf.format(now));
// Format the date in GMT time zone (again), since the time ** ERROR MIGHT **
// zone of the formatter is still set to GMT ** BE HERE **
String standdardTimeStr = sdf.format(now);
// Parse the GMT date string as-if it is in local time zone ** OR MAYBE HERE **
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = sdf2.parse(standdardTimeStr); // Date value here is wrong
// Format the bad date value back to string in the same time
// zone, which means you get GMT time back, even though that
// is not the value of the `date` variable
System.out.println("standard input time:"+ sdf2.format(date));
// Do it again, same result, because the time zone is changed ** ERROR HERE **
// on the wrong formatter object
sdf.setTimeZone(TimeZone.getTimeZone("GMT+6")); //or Asia/Dhaka
System.out.println("gmt+6 convertedtime:"+ sdf2.format(date));
You are missing to take the string representation of time to convert it back to local. The modified code below will give an idea on the same:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
public class TimeZoneExample {
public static void main(String[] args) throws ParseException {
Calendar cal = Calendar.getInstance();
final Date currentTime = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
String timeInCurrentTimeZone = sdf.format(currentTime);
System.out.println("Time in current time zone: " + timeInCurrentTimeZone);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String timeInGMT = sdf.format(currentTime);
System.out.println("Time in GMT: " + timeInGMT);
// Now, take this time in GMT and parse the string -- this is the key, we want to work with the time which got
// displayed not the internal representation and that's why we will get the time from string!
Date parsedTime = sdf.parse(timeInGMT);
String parsedString = sdf.format(parsedTime);
System.out.println("(GMT) Time in Parsed String: " + parsedString); // here it will show up it in GMT as sdf is still set to GMT
// Change the zone for sdf
sdf.setTimeZone(TimeZone.getTimeZone("GMT+6")); // or Asia/Dhaka
System.out.println("(Local) Time in Parsed String: " + sdf.format(parsedTime)); // here it you will see the zone difference
}
}
Note: You will get better picture if you take fixed time instead of current time.
I'm trying to convert a Brazil local date to UTC format. I have developed my solution but I'm sure that it can be improved. I have been searching for others questions but without success.
My problem is that when I process the Date object with:
Instant endDateTime = questionDate.toInstant();
I receive a UTC date as "2017-11-16T00:00:00Z" but this should be Brazil local date (not correct because it has a trailing "Z") and when I try to convert to UTC, I receive the same output.
In another hand, if I use ZoneDateTime class and build the date with LocalDateTime object I lose the seconds in the output: "2017-11-16T02:00Z". This happens when I use:
LocalTime.of(hour, minutes, seconds);
I search into LocalTime class and I think this is because minutes or seconds are 0 but I'm not sure of it.
Problems of the solution:
The response hasn't seconds
I hope Java 8 has a set of functions to make this more simple and clear
Precondition:
I can't use Joda library
Result has to be OffsetDateTime class
Input: Date "2017-11-16"
Output: "2017-11-16T02:00:00Z"
This is my solution:
private static OffsetDateTime processDate(Date questionDate) {
Instant endDateTime = questionDate.toInstant();
ZoneId zoneId = ZoneId.of(ZONEID);
String [] date = endDateTime.toString().split("T");
LocalDateTime localDateTime = convertLocalTimeToUtc(date);
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zoneId);
ZonedDateTime utcDate = zonedDateTime.withZoneSameInstant(ZoneOffset.UTC);
return utcDate.toOffsetDateTime();
}
private static LocalDateTime convertLocalTimeToUtc(String[] dateFromCountry) {
LocalDate date = processDate(dateFromCountry[0]);
LocalTime time = processTime(dateFromCountry[1]);
return LocalDateTime.of(date, time);
}
private static LocalDate processDate(String dateFromCountry) {
String [] partsOfDate = dateFromCountry.split("-");
int year = Integer.parseInt(partsOfDate[0]);
int month = Integer.parseInt(partsOfDate[1]);
int day = Integer.parseInt(partsOfDate[2]);
return LocalDate.of(year, month, day);
}
private static LocalTime processTime(String dateFromCountry) {
String [] partsOfTime = dateFromCountry.split(":");
int hour = Integer.parseInt(partsOfTime[0]);
int minutes = Integer.parseInt(partsOfTime[1]);
int seconds = Integer.parseInt(partsOfTime[2].substring(0,1));
return LocalTime.of(hour,minutes,seconds);
}
If your input is a java.util.Date, you can get rid of all the string manipulation:
//simulate your input
Instant input = Instant.parse("2017-11-16T00:00:00Z");
Date d = Date.from(input);
//transformation code starts here
Instant instant = d.toInstant();
ZonedDateTime localInstant = instant.atZone(ZoneOffset.UTC);
ZonedDateTime sameLocalInBrazil = utcInstant.withZoneSameLocal(ZoneId.of("Brazil/East"));
OffsetDateTime sameInstantUtc = sameLocalInBrazil.toOffsetDateTime()
.withOffsetSameInstant(ZoneOffset.UTC);
This return an OffsetDateTime with value 2017-11-16T02:00Z as you expect.
Note that an OffsetDateTime has no formatting - so the object does know that its seconds are set to 0 but the default toString method doesn't print them. If you want to print it with seconds, you can use a formatter:
//Formatting
System.out.println(sameInstantUtc.format(DateTimeFormatter.ISO_INSTANT));
which prints 2017-11-16T02:00:00Z
If your input is a java.sql.Date, you can use a slightly different strategy:
LocalDate d = sqlDate.toLocalDate();
ZonedDateTime localInstant = d.atStartOfDay(ZoneOffset.UTC);
The rest of the code would be the same.
I store the date in UTC long and displayed in user timezone. But when I try to store only days without time it misleading to different dates.
Eg: Scheduling event on 05/06/2016 (06 May 2016). This date is unique for all regions without timezone. If user from GMT+5:30 timezone trying to add a event on 05/06/2016 then it ISO-8601 format is 2016-05-05T16:00:00.000Z and milliseconds is 1462464000000.
Then user from GMT timezone try to view this event. The date will be 05/05/2016 instead of 05/06/2016.
Is there any way to convert date without any timezone.
Java 8 provides the solution for your problem. If you can use Java 8, use java.time.LocalDate which represents only the date without the time. Store the long value returned by toEpochDay method.
A sample code is given below:
LocalDate date = LocalDate.of(2016, 5, 4);
// Store this long value
long noOfDays = date.toEpochDay(); // No of days from 1970-01-01
LocalDate newDate = LocalDate.ofEpochDay(noOfDays);
System.out.println(newDate); // 2016-05-04
Always store the whole timestap.
Whenever you want to display just convert the timestamp to whichever timezone you want to convert it to & display it.
These would help in conversions: (Time-stamp to Date or viseversa)
// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );
// Date to timestamp
long timestamp = d.getTime();
//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();
Refer : convert TimeStamp to Date in Java
You may display different date formats using SimpleDateFormat.
Eg:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainClass {
public static void main(String[] args) {
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
Date date = format.parse("12/31/2006");
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
// formatting
System.out.println(format.format(new Date()));
}
}
My application receives timestamp in string format and we used parse() method in SimpleDateFormat class to convert that String to Timestamp object. My application is running in America/New_York timezone, so we faced daylight savings time issue for timestamps between March 9th 2.00 to 2.59 am. We fixed this issue by modifying default timezone properties to make sure all the daylight savings fields are reset to zero. But when we created current timestamp object using java.util.Date class after daylight savings has been changed (March 22), it showed up as 1 hour less than the actual current timestamp. This is because of changing the properties of default timezone.
public class DateTest {
static TimeZone defaultTimeZone = TimeZone.getDefault();
Timestamp timestamp1;
public static void main(String[] args) throws Exception {
DateTest dateTest = new DateTest();
System.out.println("Current date before changing Timezone:" + new java.util.Date());
//Adds one hour extra to the actual timestamp
System.out.println("Converted Timestamp with Daylight:" + convertStringToTimestamp("2014030902101900"));
System.out.println("=====================================================================");
//Displays as the actual timestamp
dateTest.setTimestamp1(convertStringToTimestampWithoutDaylight("2014030902101900"));
System.out.println("Converted Timestamp with Daylight savings:" + dateTest.getTimestamp1());
//1 hour is reduced compared to current timestamp as Daylight savings time is removed
System.out.println("Current date after changing Timezone:" + new java.util.Date());
System.out.println("=====================================================================");
//Reset back to the original timezone
TimeZone.setDefault(defaultTimeZone);
Displays current timestamp
System.out.println("Current date after Timezone reset:" + new java.util.Date());
//Adds one hour again
System.out.println("Converted Timestamp after Timezone reset:" + dateTest.getTimestamp1());
System.out.println("=====================================================================");
}
}
We are using both current timestamp object and the string to timestamp conversion in our project. I tried with Joda-Time also, but at the end we need Timestamp object when Joda-Time is converted to Timestamp, daylight savings time is being added.
DateTime dateTime = DateTime.now();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateTime.toDate());
System.out.println("Current Timestamp:" + new Timestamp(calendar.getTimeInMillis()));
LocalDateTime localdateTime = LocalDateTime.parse("2014030902101100", DateTimeFormat.forPattern("yyyyMMddHHmmssSS"));
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(localdateTime.toDate());
System.out.println("Converted Timestamp:" + new Timestamp(calendar2.getTimeInMillis()));
Output:
Current Timestamp:2014-03-22 09:15:09.478
Converted Timestamp:2014-03-09 03:10:11.0
In your parallel thread on LinkedIn you stated that you do not know what time zone your timestamps corresponds to. In most cases this is bad. But if this is indeed the situation you are in, you are free to treat them as timestamps in any timezone you choose. If you don't know whether the timezone to which your timestamps correspond has daylight savings and if does, what rules they follow, your safest choice is to consider them belonging to a time zone that doesn't have daylight savings. I would suggest using UTC. So, before parsing or formating a timestamp you need to set the timezone of the SimpleDateFormat to UTC:
public static void main(String[] args) throws Exception {
Date date = parseTimestamp("2014030902101100");
System.out.println("Parsed date: " + formatDate(date));
date = parseTimestamp("2014032202101100");
System.out.println("Parsed date: " + formatDate(date));
}
private static Date parseTimestamp(String timestamp) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse(timestamp);
return date;
}
private static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
return sdf.format(date);
}
The output is:
Parsed date: 2014-03-09 02:10:11.00 UTC
Parsed date: 2014-03-22 02:10:11.00 UTC
You can try to parse the string with SimpleDateFormat,
something like
SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSz");
Date date = sd.parse("2014030902101100GMT-05:00");
and for the z (timezone) parameter you could add GMT-05:00 (New York offset from GMT/UTC) to the timestamp string that you have at hand.
After this you can convert to what ever you would like.
simpledateforamt.parse will give you date (java.util.date).
Convesion from date to Timestamp is straight forward.
long ms = date.getTime();
Timestamp t = new Timestamp(ms);
DateTime dateTime = DateTime.now();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateTime.toDate());
System.out.println("Current Timestamp:" + new Timestamp(calendar.getTimeInMillis()));
LocalDateTime localdateTime = LocalDateTime.parse("2014030902101100",
DateTimeFormat.forPattern("yyyyMMddHHmmssSS"));
System.out.println("Converted Timestamp:" + Timestamp.valueOf(localdateTime.toString("yyyy-mm-dd hh:mm:ss")));