How to Convert JavaScript Date to Date in Java? - java

I need to convert JsDate to java.util.Date. I searched but I couldn't find anything. So could you help me with this problem?
Edit: I do this conversion process on GWT screen. I have Datepicker on screen and it gives me JsDate value when I use it's getValue() method. So I'm supposed to put this value into the property of an object which has Date type.
ObjectName.setDate(PickerName.getValue());
I hope my edit will be more clear.
Edit2:
This line is the solution of my problem:
myObject.setDate(new Date((long) myPicker.getValue().getTime()));

The best way of dates conversion is using time in milliseconds, UTC. Both JS Date object and java.util.Date class support conversion to milliseconds (getTime()) and instantiating from milliseconds (using constructor).

You can create a java.util.Date object from the 'time since epoch' value of the JS Date
javascript
var d = new Date().getTime();
java
// get value from client (ajax, form, etc), and construct in Date object
long valueFromClient = ...
Date date = new Date(valueFromClient);
String formatted = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);

If people like me are forced to parse a JS-formatted date string (as the result of (new Date()).toString() in JavaScript), here is the SimpleDateFormat spec I used:
DateFormat jsfmt = new SimpleDateFormat("EE MMM d y H:m:s 'GMT'Z (zz)");
If you have control of the producer of the dates, I concur that using timestamps or at least .toUTCString() is definitely more robust.

You may want this:
java:
String jsDate="2013-3-22 10:13:00";
Date javaDate=new SimpleDateFormat("yy-MM-dd HH:mm:ss").parse(jsDate);
System.out.println(javaDate);

ISO 8601 and java.time
ISO 8601 is the international standard for date and time including date and time formats. About any programming language has support for it, including both JavaScript and Java.
In JavaScript produce a string in ISO 8601 format using Date.toISOString(). We don’t need any formatter.
var d = new Date();
var n = d.toISOString();
console.log(n);
The result is somewhat human readable as long as you remember that it’s in UTC, denoted by the trailing Z.
In Java parse the string using Instant.parse(). We don’t need to specify any formatter here either.
String stringFromJavaScript = "2021-07-12T05:54:03.365Z";
Instant inst = Instant.parse(stringFromJavaScript);
System.out.println(inst);
Output:
2021-07-12T05:54:03.365Z
The question asked for a java.util.Date for the result from a date picker. We should avoid using java.util.Date for this both because despite the name a Date does not represent a date and because the Date class is poorly designed and long outdated. For a date without time of day a LocalDate is appropriate:
LocalDate date = inst.atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(date);
In my time zone the output was:
2021-07-12
The conversion is time zone dependent and will only be correct if the default time zone of the JVM (or which time zone you pass to atZone()) is the same as used by the date picker.
If you do need a Date for a legacy API not yet upgraded to java.time:
Date oldfashionedDate = Date.from(inst);
System.out.println(oldfashionedDate);
Mon Jul 12 07:54:03 CEST 2021
Links
Wikipedia article: ISO 8601
Oracle tutorial: Date Time explaining how to use java.time.

I would suggest using the DateFormat parse method (doc can be found here). It can parse a string representation of a date and return a java.util.Date.

JS Date --
new Date()
Wed Aug 14 2019 14:54:38 GMT+0530 (India Standard Time)
Java Date --
new Date().toISOString()
"2019-08-14T09:25:50.136Z"

Related

Remove the day name from date and set it as only 'yyyy-MM-dd HH:mm:ss' [duplicate]

This question already has answers here:
Java Date changing format [duplicate]
(4 answers)
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
(8 answers)
Closed 5 years ago.
I'm trying to get the current day's date at 6 am in the format yyyy-MM-dd HH:mm:ss, but it shows as : Wed Dec 20 06:00:00 CST 2017
This is my code:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 06:00:00");
Date date0 = new Date();
String x = dateFormat.format(date0);
try{
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = formatter.parse(x);
}
catch (Exception e){}
java.util.Date is a container for the number of milliseconds since the Unix Epoch, it doesn't not maintain any kind of internal formatting concept, instead, when you print it, it use Date#toString which generally uses the current Locale to provide a human readable representation of the value.
While I'm sure you could continue to mess about with Date to make this work, a much simpler approach would be to take advantage of the newer Date/Time API, something like...
LocalDateTime now = LocalDateTime.now();
LocalDateTime then = now.withHour(6).withMinute(0).withSecond(0).withNano(0);
String formatted = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(then);
System.out.println(formatted);
Which, for me, prints out 2017-12-21 06:00:00
TL;DR
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
LocalDate date0 = LocalDate.now(ZoneId.of("America/Winnipeg"));
String at6Am = date0.atTime(LocalTime.of(6, 0)).format(formatter);
System.out.println(at6Am);
Running just now this printed
2017-12-21 06:00:00
Details
The classes that you use, Date and SimpleDateFormat, have been around since Java 1.0, some 20 years. They have proved to be poorly designed and cumbersome to use. Maybe for that reason too, much has been written about them, and from searching the web you could easily get the impression that these are the classes you should use. On the contrary, they are the classes you should avoid. Their replacement came out with Java 8, it will soon be 4 years ago.
Formatters are for formatting and parsing. You shouldn’t use a formatter, even less two formatters, for changing the time-of-day to 6 AM.
It is never the same date everywhere on the globe. So getting today’s date is an operation that depends on a time zone. I have made the time zone explicit in my code so the reader will also be aware of this fact. Please substitute your desired time zone if it didn’t happen to be America/Winnipeg.
You are modifying existing software. If you got an old-fashioned Date object from it, first convert it to the modern Instant type, then use the modern API for further operations. For example:
Date date0 = getOldfashionedDateFromLegacyApi();
String at6Am = date0.toInstant()
.atZone(ZoneId.of("America/Winnipeg"))
.with(LocalTime.of(6, 0))
.format(formatter);
What went wrong in your code?
I don’t think there’s anything really wrong with the code in your question. You wanted your date-time formatted as 2017-12-20 06:00:00, and you got that in the string x in the third code line. Be happy with that and leave out the remainder of the code.
There is no such thing as imposing the format on the date-time objects, (no matter if we talk the outdated or the modern API). Formatting a date-time means converting it to a String in the desired format.
After parsing, you need to format it as follows: formatter.format(date). So modify your code as follows:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 06:00:00");
Date date0 = new Date();
String x = dateFormat.format(date0);
try{
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = formatter.format(formatter.parse(x));
}
catch (Exception e){}

Java - SimpleDateFormat formatter to return epoch time with milliseconds [duplicate]

This question already has answers here:
Convert a date format in epoch
(6 answers)
Closed 5 years ago.
I am very new to Java and coding in general - I have some code which returns a timestamp in the following format yyyy.MM.dd HH:mm:ss:ms which is shown below:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss:sss");
This returns:
2017.07.19 11:42:30:423
Is there a way to edit the "SimpleDateFormat formatter" code above to return the date/time as an epoch timestamp that includes milliseconds so that the value returned is formatted as per the below?
1500464550423
I'm hoping that I can amend the ("yyyy.MM.dd HH:mm:ss:sss") part of the SimpleDateFormat formatter code to do this.
Any help or advice is much appreciated.
Thanks
You have a simple error in the use of case in your format pattern string (these are case sensitive). And worse, you are using the old and troublesome SimpleDateFormat class. One of the many problems with it is it’s not telling you what the problem is.
So I recommend you use the modern Java date and time API instead (I am deliberately using your format pattern string verbatim):
String receivedTimetamp = "2017.07.19 11:42:30:423";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:sss");
LocalDateTime dateTime = LocalDateTime.parse(receivedTimetamp, parseFormatter);
System.out.println(dateTime);
This code throws an IllegalArgumentException: Too many pattern letters: s. I hope this calls your awareness to the fact that you are using two s’s for seconds and three s’s for fraction of second. If it still isn’t clear, the documentation will tell you that lowercase s is correct for seconds, while you need uppercase S for the fraction. Let’s repair:
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:SSS");
Now the code prints 2017-07-19T11:42:30.423, so we have managed to parse the string correctly.
To convert to milliseconds we are still missing a crucial piece of information: in what time zone should the timestamp be interpreted? I think the two obvious guesses are UTC and your local time zone (which I don’t know). Try UTC:
System.out.println(dateTime.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli());
This produces 1500464550423, which is the number you asked for. I suppose we’re done.
If you wanted your JVM’s time zone setting instead, use .atZone(ZoneId.systemDefault()) instead of .atOffset(ZoneOffset.UTC), but beware that the setting may be altered by other software running in the same JVM, so this is fragile.
First of all, check the documentation of SimpleDateFormat. The pattern that corresponds to milliseconds is an uppercase S, while the lowercase s corresponds to seconds. The problem is that SimpleDateFormat usually doesn't complain and try to parse 423 as seconds, adding this amount to your end date (giving an incorrect result).
Anyway, SimpleDateFormat just parses a String to a java.util.Date or formats the Date to a String. If you want the epoch millis value, you must get it from the Date object:
// input string
String s = "2017.07.19 11:42:30:423";
// use correct format ('S' for milliseconds)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss:SSS");
// parse to a date
Date date = formatter.parse(s);
// get epoch millis
long millis = date.getTime();
System.out.println(millis); // 1500475350423
The problem is that SimpleDateFormat uses the system's default timezone, so the final value above (1500475350423) will be equivalent to the specificed date and time in my system's timezone (which can be different from yours - just for the record, my system's default timezone is America/Sao_Paulo). If you want to specify in what timezone this date is, you need to set in the formatter (before calling parse):
// set a timezone to the formatter (using UTC as example)
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
With this, the result for millis will be 1500464550423 (the equivalent to the specificed date and time in UTC).
To do the opposite (create a date from the millis value), you must create a Date object and then pass it to the formatter (also taking care of setting a timezone to the formatter):
// create date from millis
Date date = new Date(1500464550423L);
// use correct format ('S' for milliseconds)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss:SSS");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// format date
String formatted = formatter.format(date);
Java new date/time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
As the input String has no timezone information (only date and time), first I parsed it to a LocalDateTime (a class that represents a date and time without timezone). Then I convert this date/time to a specific timezone and get the millis value from it:
// input string
String s = "2017.07.19 11:42:30:423";
// use correct format ('S' for milliseconds)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:SSS");
// as the input string has no timezone information, parse it to a LocalDateTime
LocalDateTime dt = LocalDateTime.parse(s, formatter);
// convert the LocalDateTime to a timezone
ZonedDateTime zdt = dt.atZone(ZoneId.of("Europe/London"));
// get the millis value
long millis = zdt.toInstant().toEpochMilli(); // 1500460950423
The value is now 1500460950423, equivalent to the specified date and time in London timezone.
Note that the API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
You can also use ZoneOffset.UTC constant if you want to use UTC.
To do the opposite, you can get the millis value to create an Instant, convert it to a timezone and pass it to the formatter:
// create Instant from millis value
Instant instant = Instant.ofEpochMilli(1500460950423L);
// use correct format ('S' for milliseconds)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:SSS");
// convert to timezone
ZonedDateTime z = instant.atZone(ZoneId.of("Europe/London"));
// format
String formatted = z.format(formatter);
First advice is to move to java8 java.time API instead of learning the broken java.date API
then do:
Instant i = Instant.now();
System.out.println(i.toEpochMilli());
in your case you can do:
LocalDateTime myldt = LocalDateTime.parse("2017-06-14 14:29:04",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(myldt.toInstant(ZoneOffset.UTC).toEpochMilli());
note that as soon as you play more with the api you will find more ways to achieve the same thing, at the end you will end invoking toEpochMilli
String strDate = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
ZonedDateTime zdt = ZonedDateTime.parse(strDate,dtf);
System.out.println(zdt.toInstant().toEpochMilli()); // 1055545912454
You can try
long time = System.currentTimeMillis();
If you have a java.util.Date then invoking getTime() will return the number of millis since the epoch. For example:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss:sss");
Date dateToBeFormatted = new Date();
// this will print a datetime literal on the above format
System.out.println(formatter.format(dateToBeFormatted));
// this will print the number of millis since the Java epoch
System.out.println(dateToBeFormatted.getTime());
The key point here is that in order to get the number of millis since the epoch you do not need a SimpleDateFormatter because the number of millis since the epoch is a property of the Date.

Obtaining the ISO 8601 date format, e.g.: 2009-06-15T13:45:30

How do you format your date in ISO 8601? E.g.: 2009-06-15T13:45:30
Is there a standard way of generating it from Java without having to create a DateTimeFormatter with a letter pattern?
I see it used in MS documentation:
Standard Date and Time Format Strings
I think this is the commonly referred to as "ISO" date.
Documented in wikipedia], giving examples such as:
Date: 2017-02-21
Combined date and time in UTC: 2017-02-21T10:26:42+00:00
2017-02-21T10:26:42Z
20170221T102642Z
The one thing to be clear: your examples go without any time zone information; so they should be assumed to be "local time".
In this String, T is just Time component in a standard ISO 8601 date time string represented as <date>T<time>. Wikipedia has a detailed page about this standard format.
In java, you can do this to use it
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
I have used GMT here just for example. You can set the time zone according to your need. To get more information about TimeZone here is the docs link
ISO-8601
A single point in time can be represented by concatenating a complete date expression, the letter T as a delimiter, and a valid time expression. For example, "2007-04-05T14:30".
The format of such date is a local date time of ISO 8601, without the time-zone.1 According to Wikipedia, date and time expressed according to ISO 8601 are:
Date: 2017-02-21
Combined date and time in UTC: 2017-02-21T12:34:46+00:00
2017-02-21T12:34:46Z
20170221T123446Z
...
There're several ways to create strings with such format in Java. In Java 8, the easiest way is to use the built-in parsing pattern of LocalDateTime. The reason why I don't use ZonedDateTime is that the time-zone of this date is unknown.
// str -> date
LocalDateTime d = LocalDateTime.parse("2009-06-15T13:45:30");
// date -> str
String text = d.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
1 ISO 8601: Time zone designators
Easy ways to obtain ISO 8601 in Java:
static void time() {
final DateTimeFormatter fmt = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS).format(fmt);
Instant.now().atOffset(ZoneOffset.ofHours(1)).truncatedTo(ChronoUnit.SECONDS).format(fmt);
Instant.now().atOffset(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS).format(fmt);
OffsetDateTime.parse("2007-12-03T10:15:30+01:00").format(fmt);
LocalDateTime.parse("2009-06-15T13:45:30").format(fmt);
}

JAVA : Get the time of different timezone

I'm currently a developing a sync module for one of my applications. I'm syncing the records between local and server based on LastUpdated time, which is nothing but a timestamp. The server is of Singapore, so how can I set the timezone to Singapore in my Android application?
I have tried,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("VST") );
and,
Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Asia/Singapore"));
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
Still no luck.
Or is there any way I can set the common timezone for both local and server? Server side language is ASP.Net
Your SimpleDateFormat example is almost correct. I believe you want SGT for Singapore and you need to call DateFormat.format(Date). You might also pass the TimeZone to Calendar.getInstace(TimeZone) like
TimeZone tz = TimeZone.getTimeZone("SGT");
sdf.setTimeZone(tz);
System.out.println(sdf.format(Calendar.getInstance().getTime()));
System.out.println(Calendar.getInstance(tz));
Joda-Time
When doing anything significant with date-time work, you should avoid the java.util.Date and java.util.Calendar classes as they are notoriously troublesome, confusing, and flawed. Instead use the Joda-Time library which does work in Android.
ISO 8601
Your string input is close to standard ISO 8601 format. Just replace the SPACE with a T. Then pass the result to the constructor of DateTime along with a DateTimeZone object representing the intended time zone of that string. Search StackOveflow for hundreds of examples.
UTC
As Elliott Frisch commented, on the server-side you should be working and storing date-time values all in UTC. Convert to local zoned values only when expected by the user in the user interface.
The server itself should be set to UTC, or if not possible then set to Reykjavík Iceland. But your programming should never assume the server is so set. Your programming should always specify the desired time zone.
Search StackOverflow for hundreds of examples and discussion of these points.
Finally, this is how I solved it.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
TimeZone tz = TimeZone.getTimeZone("Asia/Singapore");
sdf.setTimeZone(tz);
java.util.Date date= new java.util.Date();
Timestamp local = new Timestamp(date.getTime());
String strDate = sdf.format(date);
System.out.println("Local in String format " + strDate);

How to modify my code to only get the time portion of a date?

I've got the following code:
Date time = new SimpleDateFormat("HH:mm").parse("8:00");
When I call time.toString(), the following is produced:
Thu Jan 01 08:00:00 CET 1970
Is there any way I can extract just the 8:00 from it? I have searched far and wide and have not found any way to do it using the standard SimpleDateFormat.
When I call time.toString(), the following is produced
Yes, it would be - because you're calling Date.toString. A Date value has no concept of format.
Is there any way I can extract just the 8:00 from it?
Whenever you want to convert to a string, you should use a DateFormat. So use the same format that you parsed in.
Alternatively, use Joda-Time, which has a LocalTime type specifically for "time of day", and has a handy parse method. You should still use a formatter every time you want to convert to a string, but at least the value will be easier to work with and more descriptive before then.
LocalTime localTime = LocalTime.parse("8:00");
To format this, you can use something like ISODateTimeFormat.hourMinute() or if you might have more precision, perhaps ISODateTimeFormat.hourMinuteSecond() - see the docs for all of the many options available.
recycle your original SimpleDateFormat Object
SimpleDateFormat format = new SimpleDateFormat("HH:mm")
Date time = format.parse("8:00");
String outString = format.format(time);
in case you were wondering, Here's some more information on DateTime Masks
Use the same SimpleDateFormat instance to format date into string.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date time = sdf.parse("8:00");
System.out.println(sdf.format(time));
This will print:
08:00
java.util.Date class represents a specific instant in time, with millisecond precision.
API says java.util.Date.toString()
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
In order to format date's use SimpleDateFormat class
System.out.println(new SimpleDateFormat("HH:mm").format(time));

Categories

Resources