This question already has answers here:
Generic support for ISO 8601 format in Java 6
(2 answers)
Closed 7 years ago.
I have the following strings which are coming from external server -
"2015-02-25T04:23:34.874-08:00", "2015-02-25T12:22:49.275Z"
I have to show these strings in my site along with the time zone which is available in the above strings.
Following is the format to show the date in my site -
"Feb 25, 2015 03:23 AM, GMT-08:00", "Feb 25, 2015 12:22 AM, GMT"
In JAVA 7 we have new pattern character 'X' to resolve this. We can parse both these values using the single pattern
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
But I am stuck with JAVA 6. What is the right pattern to use for JAVA 6 ?
The incoming date does not depict the timezone, still if you are sure that you would be getting all times in GMT, then you can simply format the incoming date using SimpleDateFormat and get you desired format.
You have an XSD dateTime on your hands which is notoriously hard to parse using standard java (this might have changed in java 8?)
The timezone is not compatible with the SimpleDateFormat parser nor is the random number of milliseconds (can be more than 3 per the spec).
I have not used it but I'm pretty sure Joda time has an easy solution for this. In case you're interested, here is some custom code I wrote a long time ago that parses them as well: https://github.com/nablex/types-base/blob/master/src/main/java/be/nabu/libs/types/utils/TimeFormat.java
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
dateFormat.format("2015-02-25T04:23:34.874-08:00")
The format is customizable.
Related
I'm developing an android application and I use GSON to get the data from the server, I'm working on both APIs of Facebook and Imgur and the same issue happens. How can I convert a date from milliseconds format to a human-readable format like for example 1584780523 and I want to convert it to any format, for example, 25, Mar 2020.
What I tried to do!
• Get Data
#SerializedName("datetime")
#Expose
private long datetime;
// setters and getters
• In my adapter after getting DATETIME I parse it to a human-readable format
// Get Datetime.
long getDate = data.getDatetime();
// Parse it in this format for example.
DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
Date result = new Date(getDate);
// Set Result (Human-Readable date)
date.setText(dateFormat.format(result));
• But here is the problem! It gives me date like this
19 Jan 1970 09:54:00:533 +0200
Why the output at the 1970s. I saw something like that is the default output of Datetime? But in the same case, it gives me on the other items on my RecyclerView the same output but the last three digits changes!
Here what I'm asking!
1- Why we use (a lot of people use long instead of int?
2- Why the output gives me that and how can I fix this?
3- In other APIs like Youtube they use the regular DateTime why Facebook and Imgur changes them?
Note: I searched about my question for 3 days but I didn't get any answers or relative questions on StackOverflow so, I asked here. All of them or most are for PHP and JavaScript I need an example in Java Android Studio
Thanks.
Your 1584780523 value is in seconds, not milliseconds.
long secondsSinceEpoch = 1584780523;
long millisSinceEpoch = secondsSinceEpoch * 1000L;
Date date = new Date(millisSinceEpoch);
System.out.println(date);
SimpleDateFormat fmt = new SimpleDateFormat("d, MMM yyyy", Locale.US);
System.out.println(fmt.format(date));
Output1
Sat Mar 21 04:48:43 EDT 2020
21, Mar 2020
1) I'm in America/New_York time zone
1- Why we use (a lot of people use long instead of int?
This is to avoid the year 2038 problem. While for example 1584780523 does fit into an int (a 32 bits signed integer), only dates and times up to January 19 2038 03:14:07 UTC can be represented. When writing a program today, we cannot be very sure that no one will ever use our code for dates and times after that point. So we use long instead. After the year 2000 problem (using two digit years leading to problems for dates in year 2000 and later) I guess the IT world has made a sort of a commitment not again to use date and time representations that have an end date within our lifetime.
2- Why the output gives me that and how can I fix this?
Andreas has already explained this part: Because you were treating your seconds as milliseconds. It’s a common mistake.
BTW I recommend using a proven library for the conversion. The comments have already mentioned:
Instant.ofEpochSecond(timestamp)
While multiplying by 1000 works (on a long, not on an int because of overflow), doing your date and time conversions by hand is a bad habit to get into because they very often get more complicated than you think, and the risk of errors is great. Also using a library method with a nice name much better conveys why you are multiplying by 1000.
3- In other APIs like Youtube they use the regular DateTime why
Facebook and Imgur changes them?
I guess it’s because they didn’t know better back when they designed the API. There’s an international standard for transmitting dates and times, ISO 8601, and using it efficiently prevents mistakes like yours, so this is what they should have used. Even if they have understood that later, now a lot of programs rely on the old way, so changing it now would also be risky.
Links
Wikipedia article: Year 2038 problem
A few related Stack Overflow questions out of many:
Java: Date from unix timestamp
Converting Long to Date in Java returns 1970
android timestamp parsing gone wrong(always in 1970)
Wikipedia article: ISO 8601
This question already has answers here:
How can I set date and time formatting in Java that respects the user's OS settings
(7 answers)
How to get the current date/time in Java [duplicate]
(28 answers)
Closed 3 years ago.
I'm trying to read current system date and time format in java, but after analysing i couldn't find any method regarding this, so can anyone help me out.This is what i want read from java.
To get a DateTimeFormatter for the current system locale, you can use DateTimeFormatter.ofLocalizedDateTime()
The FormatStyle parameter controls whether you want long or short representation (Tuesday, April 12, 1952 AD 3:30:42pm PST versus 12.13.52 3:30pm).
A few examples and what I get on my local system:
//Tuesday, 2 April 2019 at 5:49:39 pm Australian Eastern Daylight Time
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL).format(ZonedDateTime.now())
//2 April 2019 at 5:50:20 pm AEDT
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).format(ZonedDateTime.now())
//2/4/19, 5:50 pm
DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).format(ZonedDateTime.now())
You can ask system current time only in milliseconds. And then you can transform them into DateTime:
long timestamp = System.currentTimeMillis();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = new Date(timestamp);
System.out.println(dateFormat.format(date));
You can't do it with just the Java API. The system date-time format is operating system specific, and Java has no API to read that (you can read the date-time, and the locale, but not the format). You would have to find some library that does it or write it yourself - but beware that this is going to be vastly different for every OS. E.g. for Windows you might have to read the Windows registry.
To get the locale: Locale.getDefault()
From the locale, you can probably assume the format in most cases (but not if the user chose an untypical format).
This question already has answers here:
String to Date Conversion mm/dd/yy to YYYY-MM-DD in java [duplicate]
(5 answers)
Parsing from String to Date throws Unparsable Date Error
(3 answers)
Closed 4 years ago.
I'm very confused by the following behaviour. I am returning 2 dates as Strings from a method:
getLastSupplierFlightResults()
I have added a screenshot showing the returned dates as "2018-06-20 00:00:00" and "2018-06-24 00:00:00" respectively and left the debug trace in to show the values.
I simply want to convert the dates into 20180620 format.
The methods:
.withStartDate()
.withEndDate()
...accept String values
What I don't understand is where the date "Wed Dec 06 00:00:00 GMT 2017" is coming from? This is the value that ends up being passed into the .withStart and .withEnd methods as 20171206.
As always, there is probably a simpler way of achieving my aims.
You are using the format pattern string yyyyMMdd. You are parsing the date-time string 2018-06-20 00:00:00.
2018 matches yyyy. MM means that month should be two chars, so -0 is taken for the month. And -0 or just 0 is taken to be the month before month 1 of 2018, that is, December 2017. Finally 6 is taken as the day of month. It should have been two chars too, but since there is only one digit, SimpleDateFormat settles with that. The remainder of the string is tacitly ignored.
Exactly the same thing happens when parsing the other string.
It’s the long outdated SimpleDateFormat class in a nutshell: In its attempts to be friendly and helpful it produces the most unpleasant and confusing surprises. Where you would have wished it would tell you something is wrong, it just pretends that everything is fine. It’s one of the main reasons that this class is considered troublesome, and why the replacement for the old classes came out with Java 8 more than 4 years ago. So just never use SimpleDateFormat again.
Instead look into java.time and its DateTimeFormatter.
Also don’t get date values as strings from your database. Depending on the datatype that the query returns get either a LocalDateTime or a LocalDate object. This will free you completely from parsing.
Link: Oracle tutorial: Date Time explaining how to use java.time.
Seems like your pattern doesn't match stringDates you passing.
Try to use:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
This question already has answers here:
SimpleDateFormat with TimeZone
(6 answers)
Closed 4 years ago.
Currently we are using
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX")
To format the time range to an external vendor for a range of data, for India, that formatter will give time like this:
2018-04-26T00:00:00.000+0530
However, my vendor say they cannot accept this format and it have to look like
2018-04-26T00:00:00.000+05:30
However, look like in DateTimeFormatter, whatever I choose Z/z/X/x, I don't get that format of offset. Just wonder is that a way to customize the offset to be HH:mm?
Or, I need to get the offset in second and work that our myself?
It is three x. Just tried with JavaRepl:
java.time.format.DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSxxx")
.withZone(java.time.ZoneId.systemDefault())
.format(java.time.Instant.now())
Results in
java.lang.String res10 = "2018-04-27T11:06:50.648+00:00"
After some trial and error, I saw that this is also documented in the API documentation of DateTimeFormatter but it is not easy to find (buried in a lot of other text):
Three letters outputs the hour and minute, with a colon, such as '+01:30'
DateTimeFormatter API Documentation
This question already has answers here:
Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java [duplicate]
(2 answers)
Closed 4 years ago.
I need to transform a Twitter timestampe into a Java Date object,
here is an example of a value of a Timestampe: "2015-01-06T21:07:00Z"
Can you please give me sample of java code (standard Java) doing the job?
Thank you
I recommend you take advantage of the new Date/Time API introduced in Java 8, specifically Instant as follows:
Instant.parse("2015-01-06T21:07:00Z");
You can then perform a multitude of operations, but keep in mind that the object is immutable, so any changes to the instance (that aren't chained) must be stored in a separate variable.
Actually it is ISO 8601 format for UTC time zone.
It conforms with XML DateTime format as well.
So, to get actual java.util.Calendar or java.util.Date out of it you simply can use available in JDK
Calendar twitterCalendar = javax.xml.bind.DatatypeConverter.parseDateTime("2015-01-06T21:07:00Z");
Date twitterDate = javax.xml.bind.DatatypeConverter.parseDateTime("2015-01-06T21:07:00Z").getTime();
Just be aware: java.util.Date has no Time Zone information in it. Your string is in UTC, so if you try to print value of twitterDate you will see Date/Time in TimeZone of your computer/server. Still actual value of twitterDate stays the same
millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).