What I need to do is:
1) Get user's locale from request.
2) Create new sql.Date object with current date and time, based on user's locale
3) Write it in MySQL db, column type: TIMESTAMP
What I got is:
java.util.Locale locale = request.getLocale();
java.text.DateFormat dateFormat =
java.text.DateFormat.getDateTimeInstance(
java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale );
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date( date.getTime() );
Date is OK, but have a problem with time - always 12:00:00 AM.
Any suggestions? Is there a more efficient way to do this?
Even a more compact solution ;)
java.sql.Date timeNow = new Date(Calendar.getInstance().getTimeInMillis());
There is one more simple solution for it.
use this code to get current date using java.util.Date
java.util.Calendar cal = java.util.Calendar.getInstance();
java.util.Date utilDate = cal.getTime();
java.sql.Date sqlDate = new Date(utilDate.getTime());
If you want the time, you need a java.sql.Timestamp not a java.sql.Date, and a timestamp column in the database.
Note that request.getLocale uses the value of Accept-Language heading and may not always give you the correct locale.
Getting the time zone based on the locale may not be their actual time zone .
An example: Here in Australia, the locale is 'en-AU', but we have a few time zones with up to 3 hours difference.
I'd guess in the US they have this problem too.
A possible solution is to store UTC time instead. If the user then adjusts his timezone in, say, his prefrences, or you use some other method of passing the time zone (client/browser info say via AJAX) then you can adjust the UTC time based on that using a java.util.Calendar instance.
Related
How to calculate the difference between current day and date of the object that user had previously selected from jXDatePicker swing component and that had been added as Date to that object.
In my current code at the last line I'm getting this error message:
no suitable method found for between(Date, Date)
Date currentDate = new Date();
Date objDate = obj.getSelectedDate(); //getting date the user had
//previously selected and that been
//added to object
long daysDifference = ChronoUnit.DAYS.between(objDate, currentDate);
You are mixing up the legacy Date-Time code with the new Java 8 Date-Time API. The ChronoUnit.between(Temporal, Temporal) method is from java.time.temporal package which takes two Temporal objects. It does not support the java.util.Date as an argument, hence the compilation error.
Instead of using the legacy Date class, you can use java.time.LocalDate class , and then get the difference between the two dates.
LocalDate currentDate = LocalDate.now(ZoneId.systemDefault());
LocalDate objDate = obj.getSelectedDate(); // object should also store date as LocalDate
long daysDifference = ChronoUnit.DAYS.between(objDate, currentDate);
Update
As per your comment , the objDate can only be a Date, so in this case you can use the inter-operability between the Legacy Date -Time and the Java 8 Date-Time classes.
LocalDateTime currentDate = LocalDateTime.now(ZoneId.systemDefault());
Instant objIns = obj.getSelectedDate().toInstant();
LocalDateTime objDtTm = LocalDateTime.ofInstant(objIns, ZoneId.systemDefault());
long daysDifference = ChronoUnit.DAYS.between(objDtTm, currentDate);
Update 2
As pointed out by Ole V.V in the comments, to handle Time Zone issues that may occur , calculating the difference using Instant is a better approach.
Instant now = Instant.now();
long daysDifference = obj.getSelectedDate()
.toInstant()
.until(now, ChronoUnit.DAYS);
I agree with Pallavi Sonal’s answer that when you can use the modern java.time classes, you should keep your use of the oldfashioned classes like Date to an absolute minimum. I don’t know JXDatePicker, but I see that its getDate method returns a Date. So the first thing you should do with this is convert it to a more modern thing.
It may seem from your question that in this case you are only concerned with days, not times. If this is correct, Pallavi Sonal is also correct that LocalDate is the correct class for you. I think that this conversion should work for you
LocalDate selectedDate = jXDatePicker.getDate()
.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate();
This is with a bit of reservation for time zone issues since I don’t know in which time zone the date picker is giving you the date. Once you know that, you can fill in the correct time zone instead of ZoneId.systemDefault().
Unfortunately I am not aware of a date picker component that can give you a LocalDate directly. There could well be one, I hope there is, so it’s probably worth searching for one.
We receive datetime elements relative to the UTC time like 2004-04-12T13:20:00Z.
And we would like to output the datetime in the local datetime, that is expressed with an offset relative to the UTC time like 2004-04-12T12:20:00-01:00.
With the Java 8 date and time classes this is straightforward. Only catch is, we need to go through ZoneDateTime if we want to pick om the computer’s default time zone, and then on to OffsetDateTime to get the output format you requested (another option would be formatting the date and time using a specific DateTimeFormatter; now I am relying on OffsetDateTime.toString()).
String utcTime = "2004-04-12T13:20:00Z";
OffsetDateTime dateTimeWithOffset = Instant.parse(utcTime).atZone(ZoneId.systemDefault()).toOffsetDateTime();
System.out.println(dateTimeWithOffset);
On my computer the above prints
2004-04-12T14:20+01:00
In the answer and the code I have on purpose avoided the term “local date-time” that you used in the question. This is to avoid confusion with the class LocalDateTime, which is used for a date and time without any time zone or offset information.
Use ZonedDateTime from the java 8 API.
ZonedDateTime.ofInstant(Instant.parse("2004-04-12T13:20:00Z"), ZoneId.of("CET"))
it will give you 2004-04-12T15:20+02:00[CET]
Hope the below solution works.
String date_s = "2004-04-12T13:20:00Z";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = dt.parse(date_s);
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(date); // sets calendar time/date
cal.add(Calendar.HOUR, 1); // adds one hour (do any offset that you want here)
String out = dt.format(cal.getTime());
System.out.println(out.substring(1));
Using the Java 8 JDK, you can use the java.time.Instant class to refer to UTC time. and the folloowing classes for the offset times :
java.time.LocalDate
java.time.LocalTime
java.time.LocalDateTime
Example :
Instant instant = Instant.now();
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.ofOffset("MyZoneId", ZoneOffset.ofHours(3)));
I have this simple code:
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm yyyy-MM-dd");
DateTime dateTime = formatter.withZone(DateTimeZone.forID("America/New_York")).parseDateTime("08:30 2015-06-01");
DateTime dateTime2 = formatter.withZone(DateTimeZone.forID("America/New_York")).parseDateTime("08:30 2015-12-01");
these are leap times. when I hit toString method, I got something like this:
2015-06-01T08:30:00.000-04:00
2015-12-01T08:30:00.000-05:00
which is correct, we can see UTC time - offset. But when I call getHourOfDay, I got 8 and not 4/3 as expected. What am I doing wrong? Please, share some advices here.
Well, from the Javadoc for DateTimeFormatter#withZone():
Returns a new formatter that will use the specified zone in preference to the zone of the printed object, or default zone on a parse.
So, you told the formatter to use the specific timezone on parsing AND output, and the input you gave it did NOT contain a timezone, so this is the expected result. In essence you said:
Here's a date string without timezone, parse it assuming America/New_York
Convert the date back to String, in the timezone America/New_York
This is what it did.
I am storing timezone value in database as +5:30 or +2:00 or -1:00
I am fetching data from database and changing time according to time zone in java.
Here I would like to know how can I get time according to saved timezone value.
Use Timezone and Calendar. And check SO before asking...
Examples here, or here
TimeZone tz = Calendar.getInstance().getTimeZone();
System.out.println(tz.getDisplayName());// (i.e. Moscow Standard Time)
System.out.println(tz.getID());
That should get the time zone that the computer the user is using has been set to.
Unless you want to use a complicated solution by pinging a server and making a server-side check to see where the IP came from, then that is the closest you're going to get.
Use SimpleDateFormat and setTimeZone
String timeZone = "GMT" + offset // offset is the value you store in the db( +5:30, -2:30)
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone(timeZone));
Date date = format.parse("2014-11-19T09:01:02");
I am getting a date/time string from web in the format of "yyyy/mm/dd'T'HH:MM:SS'Z'" and it is in UTC.
Now I have to identify the current time zone of device and then convert this time to my local time..
How do I do it?
(FYI, Currently, UTC time is 10:25 AM, in India current time is 3:55 PM)
Try using TimeZone.getDefault() instead of TimeZone.getTimeZone("GMT")
From the docs:
... you get a TimeZone using
getDefault which creates a TimeZone
based on the time zone where the
program is running.
EDIT: You can parse date using SimpleDateFormat (there is also the documentation on the format string there). In your case, you want to do (untested):
// note that I modified the format string slightly
SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss'Z'");
// set the timezone to the original date string's timezone
fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = fmt.parse("1998/12/21T13:29:31Z", new ParsePosition(0));
// then reset to the target date string's (local) timezone
fmt.setTimeZone(TimeZone.getDefault());
String localTime = fmt.format(date);
alternatively, use two separate instances of SimpleDateFormat, one for original and one for target time.