Convert between timezone in Java [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am reading time from the DB in format MM/dd/yyyy hh:mm a z now I want to display this time in user local timezone. So my question are:
Where should it be done client side or server side?
Is there build in lib for this purpose?
UPDATE
So I decide to do conversion in server, therefore I have method definition as following with parameter date from server and time zone offset of the client time.
public String convertToLocalDateTime(Date dateFromDB, Integer offSetMins) {
//1. dbDateInUTC = Convert dateFromDB to UTC
//2. return offSetMins + dbDateInUTC;
}
I am not sure how I can do step (1). Any suggestion?

To ensure user gets it's timezone you can do it at client side, for this you can use a library like Moment.js or date.js.
Just get the date of the server, transform it in long:
Date d = // date from server
long milliseconds = d.getTime();
Send to client and get the offset:
The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight saving time prevents this value from being a constant even for a given locale.
var offset = new Date().getTimezoneOffset();
Then you just have to get the corrected date 1 minute = 60.000 milliseconds :
var dateInMilliseconds = dateFromServer - (offset * 60000);
Also, if as #jon suggested you want to do it telling server client's timezone, get the offset and send it to java to transform the date:
long offsetMillis = offset * 60000;
Date d = new Date(offsetMillis);

In my practice, to avoid complecity and confusion, it is better to:
For operating and persisting dates within the application use UTC timezone.
Display date/time to the end user, using the local timezone.
Thus, server side all dates/times in UTC and client-side in local TZ.

Related

Is there a way to set TimeZone only for a specific class or method? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
This post was edited and submitted for review 7 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I inherited the code developed by my predecessor.
I put the code I developed here, but the time problem occurs because of TimeZone.
The problem is that if you set TimeZone globally, it is predicted that there will be problems in the existing code.
So I want to set TimeZone only for my code
Is there a way to specify Timezone only in my class file or my method?
First of all, my web server operates based on UTC, and existing codes are also based on that standard.
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Seoul"));
Using this, my webserver is pointed to Asia/Seoul and I get the time I want.
However, since this is set globally, there is concern that code written in UTC will have problems.
So it cannot be used.
Also LocalDateTime.now(Zone...); I can get the results I want by using .
However, the zone should be reflected in the already created (DB) time, not now.
In other words, 2022-06-17 15:00 is considered my time as 2022-06-18 00:00.
Rather than specifying +09:00 directly, I want a way that 2022-06-17 15:00 with TimeZone etc can be considered as 2022-06-18 00:00 by the server.
LocaDate.now allow with zone id.
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#now-java.time.ZoneId-
If its date use zone Id date.toInstant().atZone(ZoneId.of("")).toLocalDateTime()
https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#toInstant--
Use Instant and zone id
Instant instant = Instant.parse("2022-06-18 00:00");
ZoneId zoneId = ZoneId.of("Asia/Tokyo");
LocalDateTime value LocalDateTime.ofInstant(instant, zoneId);
Intent and cause of the question
The time in UTC is entered in the DB.
time : 2022-06-17 15:00
I wanted to convert this to Asia time in a Zoned LocalDateTime.
(+09:00 is required.)
The time I want: 2022-06-18 00:00
However, no matter which method was used, the time in UTC standard was output as it is.
getMyTime.atZone(...).toLocalDateTime ..
Output: 2022-06-17 15:00
While looking for a way, I found that LocalDateTime ignores (or deletes) the "zone" information.
When creating time, it can be created with zone information, but zone information has no meaning after it has already been created.
The solution
From then on, I got closer to the answer, and I found it.
ZonedDateTime.of(localDateTime,ZoneId.systemDefault())
.withZoneSameInstant(ZoneId.of("Asia/Seoul"))
.toLocalDateTime();
Get the zoneDateTime of the base time.
and the key
Create an instant with zone information through withZoneSameInstant and create it as LocalDateTime.
This works perfectly for me.

How to get current time (NOT DEVICE) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How to get today's date and time NOT DEVICE i.e actual
I have tried this and many but all they give device time
String date = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss", Locale.getDefault()).format(new Date());
You can get time details from internet and then use it. Just Internet is required.
Use android.net.sntp.SntpClient class.
SntpClient client = new SntpClient();
int timeout = 50000;
if (client.requestTime("time-a.nist.gov", timeout)) {
long time = client.getNtpTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(time);
calendar.getTime(); // this should be your date
}
1) Your code will not compile due to applying a Format with hours and minutes to a Date
2) You are using default Locale of the device so it will return the local date time.
3) You need to use a timezoned time and apply the timezone of Greenwitch to get current DateTime without any timezone applied.
Check ZonedDateTime for more informations
If I understood you correctly, you might want to get the timestamp from a NTP (Network Time Protocol) server. And java has already had libraries to support your need.
Check this out. (StackOverFlow) How to make my java app get global time from some online clock
// get current default time
System.out.println( Calendar.getInstance().getTime());
// get different time zone
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
LocalTime localTime=LocalTime.now(zoneId);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
String formattedTime=localTime.format(formatter);
System.out.println("Current time of the day in Los Angeles: " + formattedTime);

What is the difference between date format “2019-06-17-04:00” and “2019-06-17Z”? exactly what time does “2019-06-17Z” point to? [duplicate]

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.

Convert int to date in Java/Android [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to get data from a website, and when I tried to get the date of a post (expected: 13/06/2014 11:55), i got:
23377855
Can someone help me to convert this number to a date? Thanks!
You can use the standard Java Date API:
long yourNumber = 23377855;
Date date = new Date(yourNumber);
Or you can use Joda Time library, provides much better overall functionality than Java Date API:
long yourNumber = 23377855;
DateTime dt = new DateTime(yourNumber);
Java is expecting milliseconds:
java.util.Date time= new java.util.Date((long)urDateNum*1000);
So you must multiply by 1000
Docs say:
Allocates a Date object and initializes it to represent the specified
number of milliseconds since the standard base time known as "the
epoch", namely January 1, 1970, 00:00:00 GMT.
Note:
The cast to long is very important in this situation. Without it the integer overflows.

How to detect the timezone of a client?

How to get client/request timezone in jsp?
Unfortunately this information is not passed in HTTP headers.
Usually you need cooperating JavaScript to fetch it for you.
Web is full of examples, here is one http://www.coderanch.com/t/486127/JSP/java/Query-timezone
you cannot get timezone, but you can get current time from client side.i.e. through javascript and than post back. On server side, you can convert that time to GMT/UTC. The UTC shows the TimeZone.
If you just need the local timezone in order to display local times to the user, I recommend representing all times in your service in UTC and rendering them in browsers as local times using Moment.js.
My general rule is to handle and store times in UTC everywhere except at the interface with the user, where you convert to/from local time. The advantage of UTC is that you never have to worry about daylight-saving adjustments.
Note that if you want to show the age of something (e.g. "posted 3 hours ago") you just need to compare the UTC timestamp with the current UTC time; no need to convert to local times at all.
Best solution for me is sending date/time as a string, and then parse with server's timezone to get a timestamp. Timestamps are always UTC (or supposed to be) so you will not need client's TimeZone.
For example, sending "10/07/2018 12:45" can be parsed like:
SimpleDateFormat oD = new SimpleDateFormat();
oD.applyPattern("dd/MM/yyyy HH:mm");
oD.setTimeZone(TimeZone.getDefault()); // ;)
Date oDate = oD.parse(request.getParameter("time"));
Obviously you can set your specific date/time format.

Categories