I'm having issues converting the date into UTC, I'm able to get this working on a standalone java program, however, while running the same method on a server gives me a different timestamp.
Here is the method I've to convert a String date into XMLGregorianCalendar in UTC.
public static XMLGregorianCalendar convertDateToXMLGregorianCalendarInUTC(String date, String dateFormat) throws ParseException, DatatypeConfigurationException {
if (StringUtils.isBlank(date))
return null;
TimeZone timeZoneInUTC = TimeZone.getTimeZone("GMT0:00");
GregorianCalendar gregorianCalendar = new GregorianCalendar(timeZoneInUTC);
DateFormat dateFormat = new SimpleDateFormat(dateFormat);
Date dateUtil = null;
XMLGregorianCalendar xmlGregorianCalendar = null;
dateUtil = dateFormat.parse(date);
gregorianCalendar.setTime(dateUtil);
xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
return xmlGregorianCalendar;
}
With the above method when I run it on standAlone java prog. It converts the timestamp into UTC by adding 5 hours to the date passed.
public static void main(String[] args) throws ParseException, DatatypeConfigurationException {
System.out.println("DateUtil xmlGC in UTC: "+DateUtil.convertDateToXMLGregorianCalendarInUTC("03/06/2017 05:47:37", "MM/dd/yyyy HH:mm:ss"));
}
OutPut: DateUtil xmlGC in UTC: 2017-03-06T10:47:37.000Z.
However, while using the same method on tomcat - application server on the same machine, it not converting the date into UTC. Am I missing something here.,
Can someone please help me on this. Thanks in Advance.
Set Tomcat timezone
-Duser.timezone=GMT+05
Related
I'm working on Spring boot project and I want to convert a String date coming from a post request
D,100000001028686,BA0884,72087000000176,N,2,147568593,DEPOSITREFERENCE,2020-08-05
20:17:33.32691,
601123,ZAR,2500,57,24,i10c=0,i20c=2,i50c=5,iR1=2,iR2=5,iR5=8,iR10=200,iR20=1,iR50=55,iR100=60,iR200=82,0,0,0,0,000
The date that I want to convert is in Bold and need to convert that part from a #PostMapping method request parameter into one of the java.time Objects.
After searching I found some solution for the data if self without using Spring but it did not work for me and used java.util.Date, here the code I wrote so far
class Main {
public static void main(String[] args) throws ParseException {
String date = "2020-08-05 20:18:33.32692";
System.out.println(covertDate(date)); //Wed Aug 05 20:19:05 UTC 2020
}
public static Date covertDate(String date) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS");
return formatter.parse(date);
}
}
The response I got is not what I'm looking for, is there any way to solve the problem
Here the solution I found after searching for future
I used Java 8 API to solve it
class Main {
public static void main(String[] args) throws ParseException {
String sDate6 = "2020-08-05 11:50:55.555";
System.out.println(covertDate(sDate6)); //2020-08-05T11:50:55.555
}
public static LocalDateTime covertDate(String date) throws ParseException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
LocalDateTime dateTime = LocalDateTime.parse(date,formatter);
return dateTime;
}
}
In JShell (Java Version 14) I ran your code and was able to get the similar results (Granted it is in GMT and not UTC; however, the seconds are offset by the same amount as your current output):
If the question is about UTC:
I would suggest to use Instant as it avoids many of the issues that LocalDateTime has presented over the years. As mentioned in the comments is it generally best to avoid using java.util.Date and to use Instant instead (or you could use the more traditional LocalDateTime).
If you are talking about Spring's annotated #PostMapping method to parse out the date automatically you could use something like:
#PostMapping
public String postDate(#RequestParam #DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Long dateReq) {
Instant date = Instant.ofEpochMilli(dateReq);
System.out.println(date);
}
If you wanted to use your custom formatter the you could do #RequestParam #DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSSS" LocalDateTime date) as the parameter of the postDate method.
Please note that Spring's docs state that the pattern field of #DateTimeFormat uses the same patterns as java.text.SimpleDateFormat. So that could be of use.
I want to create an XMLGregorianCalendar with the following characteristics:
Time only
UTC timezone (The "Z" appended at the end)
So I would expect the date to be printed as: 18:00:00Z (XML Date).
The element is an xsd:time and I want the time to be displayed like this in the XML.
<time>18:00:00Z</time>
But I am getting the following: 21:00:00+0000. I am at -3 offset and the result is the calculation with my offset.
Why is wrong with my code?
protected XMLGregorianCalendar timeUTC() throws Exception {
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ssZZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateS = df.format(date);
return DatatypeFactory.newInstance().newXMLGregorianCalendar(dateS);
}
To get an output you've mentioned (18:00:00Z) you have to set the XMLGregorianCalendar's timeZone offset to 0 (setTimezone(0)) to have the Z appear. You can use the following:
protected XMLGregorianCalendar timeUTC() throws DatatypeConfigurationException {
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
XMLGregorianCalendar xmlcal = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(
dateFormat.format(new Date()));
xmlcal.setTimezone(0);
return xmlcal;
}
If you would like to have the full DateTime then:
protected XMLGregorianCalendar timeUTC() throws DatatypeConfigurationException {
return DatatypeFactory.newInstance()
.newXMLGregorianCalendar(
(GregorianCalendar)GregorianCalendar.getInstance(TimeZone.getTimeZone(ZoneOffset.UTC)));
}
The ouput should be something like this: 2017-08-04T08:48:37.124Z
Adding 'Z' at the end of he pattern will do the job.
DateTimeFormat.forPattern("HH:mm:ss'Z'");
I receive date as string from web service in following format 2014-02-27T11:17:00.000Z Could someone tell me how to parse it as Date time object in Java.
I tried parsing it Date.parse() but it didn't work properly.
Then I tried date formatter but it crashes the app. Could someone enlighten me please.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date d = sdf.parse("2014-02-27T11:17:00.000Z");
You can use dateformat class for that.
DateFormat sdt = new SimpleDateFormat(put your format here);
Date stime= sdt.parse(starttime);
Date etime = sdt.parse(endtime);
Starttime and end time are the strings which you want to parse
Declare a SimpleDateTimeFormat to match your datetime from C# and then use .parse() method on it to get the (Java) Date.
Example:
private static final SimpleDateFormat FORMAT_FULL_DATE = new SimpleDateFormat("yyyy-MM-dd'T'kk:mm:ss'.000Z'"); // replace kk with hh for am/pm format
public static Date getDateTimeFromString(final String string) {
try {
return FORMAT_FULL_DATE.parse(string);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
I'm trying to parse a string to get a Date object, but it's always returning Sun. December 30, 2012 for the date. Does anyone have any ideas on what I'm doing wrong?
I was using the same code using strings in YYYY-MM-dd format and it worked just fine, so I'm not sure why switching to this format is causing issues.
public static Date getDateObjFromStr(String dateStr)
{
DateFormat formatter = new SimpleDateFormat("MM/dd/YYYY");
Date dateObj;
try {
dateObj = formatter.parse(dateStr);
return dateObj;
} catch(Exception e) {
return null;
}
}
Case-sensitive
Uppercase Y represents week-based year.
Try using lowercase y instead
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Thanks for the solution,but its not working out for me. I am dealing with a scenario where I am setting date(with time and timezone information) in the oracle database.I use Ibatis to extract this date and assign it to a java Date object. I implemented my TypeHandlerCallback as follows:
public class DateTimezoneTypeHandler implements TypeHandlerCallback {
public void setParameter(ParameterSetter setter, Object parameter)
throws SQLException
{ java.util.Date date = (java.util.Date) parameter; if ( date == null ) setter.setNull(Types.TIMESTAMP); else { Timestamp timestamp = new Timestamp(date.getTime()); Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); setter.setTimestamp(timestamp, calendar); } }
#Override public Object getResult(ResultGetter getter) throws SQLException {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return getter.getTimestamp(calendar);
}
#Override public Object valueOf(String s) { throw new UnsupportedOperationException( "DateTimezoneTypeHandler.valueOf() is not supported."); } }
I have stored my date in the database in EST timezone and so getter has the date in EST time zone.Now when the date is read from the database,getResult function gets called but EST date is not not getting converted to UTC/GMT time zone. It is converting date having EST timezone to date having my local system timezone
**public Object getResult(ResultGetter getter) throws SQLException {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
return getter.getTimestamp(calendar);
}**
Following is my sql mapping:
I am not understanding what is the issue with this method implementation and why its not required functionality.
Please let me know if anyone has any suggestion/solution about this issue. I will really appreciate it.
The problem appears to be that you are not actually translating the time. Setting the timezone does not cause Calendar to convert the current value to the new timezone. Here is some example code that performs timezone translation GMT-5 (aka EST) to UTC. Note that I use Calendar.add and not Calendar.roll.
public static void main(String[] args)
{
Calendar calendar = Calendar.getInstance();
Date date;
int rawOffset;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("M/d hh:mm;ss a");
TimeZone timeZone;
date = calendar.getTime();
System.out.println(simpleDateFormat.format(date));
timeZone = TimeZone.getTimeZone("GMT-5");
rawOffset = timeZone.getRawOffset();
System.out.println(rawOffset);
calendar.add(Calendar.MILLISECOND, rawOffset);
date = calendar.getTime();
System.out.println(simpleDateFormat.format(date));
}
FWIW, our company has stopped storing Dates and Times as an Oracle timezone in the database. There is too much dependency on external configuration. Instead, we do the following:
Since asking for currentTimeMillis returns an absolute point in time, we create a TypeHandler for the Java Date class which stores the date/time in a NUMBER column in the database
Because reading millis-from-epoch is hard for humans, we add 2 functions to the database to convert from/to millis so that administrators can still write queries if they like to
The advantage of this is that you circumvent any "smart" time handling by anything outside the JVM. This is particularly handy when people enter a date in a foreign browser, pass that into your server app, and then passing it into the database.
In case you do want to store Dates in the database (sometimes you have to do these things), I personally can recommend Joda-Time for easier handling of dates, times, gregorian calendars and the likes.