This question already has answers here:
How to handle calendar TimeZones using Java?
(9 answers)
Closed 6 years ago.
I am trying to get current time of a particular timeZone but when I write this:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("America/Boise"));
System.out.println(calendar.getTime());
it always prints UTC time followed by "UTC" word maybe because on the server timeZone is set to UTC but still it shouldn't happen as I explicitly specified the timezone here.
It returns UTC because the method TimeZone.getTimeZone(String id) returns the specified TimeZone, or the GMT zone if the given ID cannot be understood. In your case, since the given ID cannot b understood, it returns the GMT Zone.
Related
This question already has answers here:
Converting date to timestamp with timezone in Java
(3 answers)
Datetime behind an hour after insertion. Daylight savings
(2 answers)
Closed 2 years ago.
I have a 'simple' problem with Java and dates. I thought it was simple but I don't understand how to solve it ! I have try a lot of things. Here is the problem.
I save a date in my postgres sql database like this.
user.setCreationDate(Timestamp.valueOf((LocalDateTime.now())));
this date is store with one hour less than the real hour here.
When I want to use it, I would like to get in database and add the UTC +1 of my local zone.
I try this but always get the date -1h...
OffsetDateTime myNewDate = bddDate.toInstant().atZone(ZoneId.systemDefault()).toOffsetDateTime()
Do you have an idea of how just get the local timezone exact hour ?
Thanks for your help !
This question already has answers here:
Get GMT Time in Java
(12 answers)
How to Parse Date from GMT TimeZone to IST TimeZone and Vice Versa in android
(4 answers)
Getting the current time millis from device and converting it into a new date with different timezone [duplicate]
(2 answers)
How to set time zone of a java.util.Date?
(12 answers)
Closed 3 years ago.
Java 8 here, I have the following code:
public class PossibleBug {
public static void main(String[] args) {
new PossibleBug().run();
}
public void run() {
buildDate("20181205");
}
public Date buildDate(final String yyyyMmDd) throws ParseException {
TimeZone expectedTz = TimeZone.getTimeZone("America/New_York");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
sdf.setTimeZone(expectedTz);
TimeZone actualTz = sdf.getTimeZone();
Date answer = sdf.parse(yyyyMmDd);
return answer;
}
}
So pretty basic stuff:
create a SimpleDateFormat and set its timezone to EST
Use the SDF to parse a date string
Result should be a date in EST as well
However at runtime, look at the debugger results:
How is this possible?!?! sdf.parse(yyyyMmDd) is returning a date formatted in GMT. Is there something I'm missing on my end or is this a bug in SimpleDateFormat?
I am able to invoke buildDate and run it from inside a different class and it seems to work fine:
Date stores no timezone. It's essentially just a wrapper around a long, storing millis after epoch.
When you print it (or when your debugger invokes the toString() method to get a string representation to display), your JVM's default timezone is used, irrespective of how it was created.
Date, despite the name, doesn't model a date: it's an instant in time.
Given that your input is "20181205", don't use Date: use classes from java.time like java.time.LocalDate.
If you take a look at the Java-Doc for SimpleDateFormat.parse(), you can see that the TimeZone might be overwritten:
The TimeZone value may be overwritten, depending on the given pattern and the time zone value in text. Any TimeZone value that has previously been set by a call to setTimeZone may need to be restored for further operations.
The documentation says: "This parsing operation uses the calendar to produce a Date. All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information. For example, the year value of the parsed Date is 1970 with GregorianCalendar if no year value is given from the parsing operation. The TimeZone value may be overwritten, depending on the given pattern and the time zone value in text. Any TimeZone value that has previously been set by a call to setTimeZone may need to be restored for further operations."
In short, SimpleDateFormat is a formatter/parser, not a utility for performing time zone conversions. If there's no TZ in the string you are parsing, you get the default value from Calendar.
Consider what would happen if you called setTimeZone, then parsed a string that actually contained a time zone itself? What would you expect to happen?
Also, note that Date doesn't contain a time zone. It's specifically defined as being the number of milliseconds since January 1, 1970, 00:00 UTC. Library functions apply a time zone when needed (like when converting to a String) and if you don't specify one, you'll get the default time zone. You see GMT because your default time zone is GMT or because your IDE always displays Date objects in GMT, and the person who said he got EST must have is default time zone set to EST.
In your case, you're parsing a string that does not contain a time zone at all. In fact, it doesn't even contain a time. Using Date to handle, uh, dates (I realize this is confusing, I mean dates without times), is likely to lead to mistakes, especially when your default time zone isn't UTC/GMT. I recommend using LocalDate and the LocalDate.parse method.
This question already has answers here:
What is this date format? 2011-08-12T20:17:46.384Z
(11 answers)
Closed 3 years ago.
I’m using XMLGregorianCalendar in my spring boot app to define a date range and using the same in the input while calling an REST service. However, when I’m calling the service from my local, I see the date is being set as “2019-06-17-04:00” in the REST input XML. If I run the same app in Openshift container, the date is being set as “2019-06-17Z” in the request XML. Can you please let me know the reason for this? And what is the difference between these two date formats?
XMLGregorianCalendar toDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar());
XMLGregorianCalendar fromDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(<some date>);
The suffix on both inputs refer to offset-from-UTC, presumably.
The -04:00 on 2019-06-17-04:00 means four hours behind UTC.
the Z on 2019-06-17Z means zero hours-minutes-seconds from UTC, that is, UTC itself. The Z is pronounced “Zulu” and is short for +00:00:00.
However, both of your inputs are meaningless. Assigning an offset to a date without a time-of-day makes no sense. Indeed, on some days such as a Daylight Saving Time (DST) cutover, a date might involve two offsets.
You should report these values to the publisher as erroneous. Educate them about the ISO 8691 standard for reporting date-time values.
This question already has an answer here:
How to save time using java.sql.Date?
(1 answer)
Closed 5 years ago.
I am trying to create a java.sql.Date object initialized to current time but it was being rounded off to midnight time . Can any of you help? I attempted below but it did not work.
new Date(new java.util.Date().getTime())
I can't explain it better than the Javadoc does:
A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
If you need time information as well, you might use java.sql.Timestamp.
This question already has answers here:
How to compare two Dates without the time portion?
(33 answers)
Closed 9 years ago.
I have a scheduler that needs to check if the incoming timestamp is current day's timestamp.
The incoming timestamp will be of the format Eg:1384956395.
How to check this in java? Please help. I am not using Joda
The epoch you posted is in seconds. Java uses milliseconds so you have to convert it and then compare the two.
long epochInMillis = epoch * 1000;
Calendar now = Calendar.getInstance();
Calendar timeToCheck = Calendar.getInstance();
timeToCheck.setTimeInMillis(epochInMillis);
if(now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)) {
if(now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR)) {
}
}
You can also change the time zone if you do not want to use the default, in case the input epoch is in a different time zone.
Assuming that your timestamp was created via System.currentTimeMillis() (or any other compatible mechanism), you can do the following:
Create a Calendar instances and set the hour, minute, second and millisecond fields to zero. This is today at 0:00:00,0.
Clone the instance and add 1 day. You'll get tomorrow at 0:00:00,0.
Now check if your timestamp is in the range between today.getTime() (inclusive) and tomorrow.getTime() (exclusive).