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();
Related
I am pulling data out of an Excel sheet, to load into Hubspot, using Java.
Here is how the data looks:
this date 2018-12-31 becomes Dec 31, 2017 once it's in side Hubspot.
This is wrong!
Here is my code:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dt = null;
try {
dt = df.parse(member.getUsageEndDate());
} catch (java.text.ParseException e3) {
//dt = null;
e3.printStackTrace();
}
Long l = dt.getTime();
If I open the data in Notepad, it looks like this: 31-May-2018
How can I get this converted properly?
tl;dr
OffsetDateTime.of(
LocalDate.parse( "2018-12-31" ) ,
LocalTime.MIN ,
ZoneOffset.UTC
)
.toInstant()
.toEpochMilli()
1546214400000
Details
Avoid legacy date-time classes
You are using troublesome old date-time classes long ago made legacy by the arrival of the java.time classes built into Java 8 and later.
ISO 8601
Your input string happens to comply with the ISO 8601 standard formats. These formats are used by default in java.time when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2018-12-31" ) ;
First moment of the day
Apparently you need the first moment of the day in UTC for that date. Use OffsetDateTime with constant ZoneOffset.UTC.
OffsetDateTime odt = OffsetDateTime.of( ld , LocalTime.MIN , ZoneOffset.UTC ) ;
Dump to console.
System.out.println( "odt.toString(): " + odt );
See this code run live at IdeOne.com.
odt.toString(): 2018-12-31T00:00Z
Count-from-epoch
You appear to want the count of milliseconds since the epoch reference date of first moment of 1970 in UTC, 1970-01-01T00:00Z. Extract an Instant object, the basic building-block class in java.time, and call its handy Instant::toEpochMilli method.
long millisecondsSinceEpoch = odt.toInstant().toEpochMilli() ;
See this code run live at IdeOne.com.
1546214400000
Going the other direction.
Instant instant = Instant.ofEpochMilli( 1_546_214_400_000L ) ;
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
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 am just trying to convert "2016-01-28T12:08:47.676706-05:00" but getting exception. Can anyone suggest me DateFormat like "yyyy-MM-dd HH:mm:ss.SSSZ" to parse the string into Date.
I hope that the code below will help you
String dateString = "2016-01-28T12:08:47.676706-05:00";
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS", Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = format.parse(dateString);
tl;dr
OffsetDateTime.parse( "2016-01-28T12:08:47.676706-05:00" )
java.time
Use the modern java.time classes that supplant the troublesome legacy date-time classes.
The legacy classes wore limited to millisecond resolution while the java.time classes have much finer resolution, nanoseconds. That is more than enough for the microseconds in your input string.
Your input complies with standard ISO 8601 format. The java.time classes use standard formats by default when parsing/generating strings. So no need to specify a formatting pattern at all.
We parse your input as a OffsetDateTime since it includes an offset-from-UTC but not a time zone.
OffsetDateTime odt = OffsetDateTime.parse( "2016-01-28T12:08:47.676706-05:00" ) ;
odt.toString(): 2016-01-28T12:08:47.676706-05:00
To see that same moment as UTC value, extract an Instant.
Instant instant = odt.toInstant() ;
instant.toString(): 2016-01-28T17:08:47.676706Z
Or adjust into a time zone, to get a ZonedDateTime object.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
zdt.toString(): 2016-01-29T06:08:47.676706+13:00[Pacific/Auckland]
To generate Strings in other formats, search Stack Overflow for DateTimeFormatter class. Already covered many times.
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)
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.
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!).