How do I convert a string of ISO-8601 datetime (ex: 2012-05-31T13:48:04Z) to number of seconds( 10 digit integer) using Java?
try this way
String DateStr="2012-05-31T13:48:04Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date d=sdf.parse(DateStr);
System.out.println(d.getTime());
output 1338452284000
From the comments of OP
getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.Source
using SimpleDateFormat and use format like yyyy-MM-dd 'T' HH:mm:ss 'Z'
tl;dr
Instant.parse( "2012-05-31T13:48:04Z" )
.getEpochSecond()
1338472084
See this code run live at IdeOne.com.
Using java.time
Much easier with the java.time classes that supplant the troublesome old legacy date-time classes.
Easy to parse your input string as the java.time classes use ISO 8601 formats by default when generating/parsing strings. So no need to specify a formatting pattern.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.parse( "2012-05-31T13:48:04Z" ) ;
I am guessing that by “seconds” you meant the number of seconds elapsed since the beginning of 1970 UTC (1970-01-01T00:00:00Z). The Instant class can tell you the number of seconds since that Unix epoch.
long secondsSinceEpoch = instant.getEpochSecond() ;
1338472084
Beware of data loss, obviously. You are ignoring any fractional second that may be present in your date-time value.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Related
I have to display a date in the format MM/dd/yyyy. The date to be displayed can be in any of the following formats
MM/dd/yyyy
MM/yyyy
yyyy
If only month and year are available and day is not available then I have to display the date in the format MM/__/yyyy leaving the day blank.
If only year is available and day and month are not available then I have to display the date in the format __/__/yyyy leaving day and month blank.
I'm able to display it properly if whole date is available i.e. day, month and year using mask formatter.
MaskFormatter formattedDate = new MaskFormatter("##'/##'/####");
but not able to display it if day or month is missing.
Is there any way to display the date leaving date and month blank?
java.time
The java.time classes built into Java 8 and later have a class for each of your needs:
LocalDate for date-only, without time-of-day, and without time zone.
YearMonth for a year and month but no date, and no time zone.
Year for just a year.
For example:
YearMonth ym = YearMonth.now( ZoneId.of( "Africa/Tunis" ) );
ym.toString(): 2018-02
All three offer a format method to which you pass a DateTimeFormatter object. You can define custom formatting patterns in that DateTimeFormatter. Search Stack Overflow as this has been covered many times already.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/__/uuuu" );
String output = ym.format( f );
02/__/2018
ISO 8601
By the way, consider using standard ISO 8601 formats to display these values as text. The format for a date is YYYY-MM-DD, and for a year-month, YYYY-MM.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I am trying to use Java to format a time in milliseconds into a date in UTC. I have the following code:
long ms = 1427590800000;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT);
cal.setTimeInMillis(ms);
Date date = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
System.out.println(dateFormat.format(date)); // 2015-03-29 02:00:00
This is printing a time in BST (i.e. using the default time-zone) rather than UTC. It seems like the time-zone being set on the calendar has no bearing on the date being printed.
The actual time in UTC is shown by the following python snippet:
import datetime
ms = 1427590800000
print datetime.datetime.utcfromtimestamp(ms/1000.0) # 2015-03-29 01:00:00
Setting the default JVM time-zone to "UTC" results in the correct date being printed, but this doesn't seem like a safe solution.
java.time
The modern approach uses the industry-leading java.time classes.
Parse as an Instant, a moment in UTC with a resolution of nanoseconds.
long input = 1_427_590_800_000L ;
Instant instant = Instant.ofEpochMilli( input ) ;
ISO 8601
Generate a string in standard ISO 8601 format.
String output = instant.toString() ;
2015-03-29T01:00:00Z
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You need to set the timezone to the formatter before formatting if you want a desired timezone.
Use dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); and then call dateFormat.format(date)
I'm trying to convert this date string 2014-07-17T22:41:17+0000 to a timestmap, similar to this: 1405645259000.
I've tried something similar to this:
String string = "January 2, 2010";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(date);
How do I convert this (2014-07-17T22:41:17+000) to a Date? What is the correct format? I'm at a loss.
Take a look at http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your date string has the same format as
yyyy-MM-dd'T'HH:mm:ssZ //Eg: 2001-07-04T12:08:56-0700
So, your code should be:
String string = "2014-07-17T22:41:17+0000";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH).parse(string);
System.out.println(date);
use this pattern:
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH).parse(string);
tl;dr
OffsetDateTime.parse( "2014-07-17T22:41:17+0000" )
.toInstant()
.toEpochMilli()
Avoid java.util.Date
Your question is easy in Joda-Time or the new java.time package in Java 8. Avoid java.util.Date and .Calendar as they are notoriously troublesome.
ISO 8601
Your String is in standard format, complying with ISO 8601. Both libraries mentioned above use ISO 8601 as their defaults for parsing and generating strings.
java.time
The OffsetDateTime class represents a moment on the timeline with an offset-from-UTC and with a resolution in nanoseconds.
OffsetDateTime odt = OffsetDateTime.parse( "2014-07-17T22:41:17+0000" );
From there you can ask for the count-of-milliseconds-since-epoch via the Instant class. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
long millisecondsSinceEpoch = odt.toInstant().toEpochMilli();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Joda-Time
Example code on Joda-Time 2.3.
long millisSinceEpoch = new DateTime( "2014-07-17T22:41:17+0000" ).getMillis();
I received from a SOAP message the follow date:
2012-11-16T02:02:05Z
How to parse to Date? What means this T and the Z in the date according with the SOAP specification?
I can parse correctly doing this way:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(paymentDate);
Thanks #vikdor!
tl;dr
Instant.parse( "2012-11-16T02:02:05Z" )
ISO 8601
Your input string is in standard ISO 8601 format. That standard defines many useful, practical, unambiguous textual formats for representing date-time values.
The ISO 8601 formats are commonly adopted by modern protocols, such as XML schema, SOAP, etc., supplanting the clumsy outmoded formats such as RFC 1123 / RFC 822.
Your particular format from ISO 8601 uses:
T to separate the year-month-day portion from the hour-minute-second portion.
Z, short for Zulu, to indicate UTC time (an offset-from-UTC of +00:00).
Using java.time
Use the modern classes in the java.time package. They use ISO 8601 formats by default when parsing/generating strings.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.parse( "2012-11-16T02:02:05Z" ) ;
Capture the current moment in UTC.
Instant instant = Instant.now() ;
Generate a string in standard format by simply calling toString.
String output = instant.toString() ;
2017-07-26T01:23:45.704781401Z
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I need to convert a timestamp string to java.util.Date. E.g.:
MMDDYYHHMMSS to MM-DD-YY HH-MM-SS
Where MM is month, DD is date, YY is year, HH is hours, MM is minutes and SS is seconds.
You can do it like this:
DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
Date date = format.parse("022310141505");
but I would strongly recommend that you use Joda Time instead. It's a better date/time library by a long, long way. In particular, the formatters/parsers in Joda Time are thread-safe, so you can reuse them freely and statically; java.text.SimpleDateFormat isn't thread-safe, so you either need to create one per thread or serialize access to it with a synchronized block.
tl;dr
java.time.LocalDateTime.parse(
"012318123456" ,
DateTimeFormatter.ofPattern( "MMdduuHHmmss" )
).format(
DateTimeFormatter.ofPattern( "MM-dd-uu HH-mm-ss" )
)
01-23-18 12-34-56
java.time
The modern approach uses the java.time classes.
Define a formatting pattern to match your input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMdduuHHmmss" ) ;
Your two-digit year will be interpreted as being 21st century ( 20xx ).
Parse as a LocalDateTime because your input string lacks any indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( "012318123456" , f ) ;
ldt.toString(): 2018-01-23T12:34:56
Generate a string in your desired format.
DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "MM-dd-uu HH-mm-ss" ) ;
String output = ldt.format( fOut );
01-23-18 12-34-56
ISO 8601
Both of your formats are terrible, for multiple reasons.
When serializing date-time values, use the standard ISO 8601 formats whenever possible. They are designed to be practical, easy to parse by machine, easy to read by humans across cultures.
For a date-time time such as yours, the T in the middle separates the date portion from the time-of-day portion.
2018-01-23T12:34:56
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
use a SimpleDateFormat with an appropriate format string (be careful to use the correct format letters, uppercase and lowercase have different meanings!).