If I have code such as this:
DateTimeParser[] parsers = {
DateTimeFormat.forPattern("yyyyMM").getParser(),
DateTimeFormat.forPattern("yyyyMMdd").getParser(),
DateTimeFormat.forPattern("yyyyMMddHHmm").getParser(),
DateTimeFormat.forPattern("yyyyMMddHHmmZ").getParser(),
DateTimeFormat.forPattern("yyyyMMddHHmmss.SSSSZ").getParser()
};
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
final DateTime dateTime = formatter
.parseDateTime(dateString);
return new Timestamp(dateTime.getMillis());
How can I determine which pattern was used? I want to force UTC timezone only in situation when no timezone is explicitly provided. ie, when Z is missing
Alternatively, how can I simply determine if a timezone was provided when parsing a joda datetime?
You can always get the zone from the code below with withOffsetParsed() and compare with your default zone
String dateString = "2016052914346.2354+0300";
DateTimeParser[] parsers = {DateTimeFormat.forPattern("yyyyMM").getParser(),DateTimeFormat.forPattern("yyyyMMddHHmmss.SSSSZ").getParser()};
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
DateTime dateTime = formatter.withOffsetParsed().parseDateTime(dateString);
DateTimeZone zone = dateTime.getZone();//+03.00
Related
I have string of a date in "iso8601" format and when I parse it using Joda "DateTime", the time zone of date changes automatically.
DateTime dateTime = new DateTime( "2017-05-22T08:10:00.000+0300" ) ;
System.out.println(dateTime);
and its output is:
2017-05-22T09:40:00.000+04:30
As you see time zone of first string is +3:00 and the time zone after parsing is +04:30. How can I parse first string without changing time zone? (so the time zone remains +03:00 even after parsing)
This constructor use default timezone of user. You need to set timezone manually with DateTime(Object object, DateTimeZone zone) construnctor.
Or, parse this string with usage of withOffsetParsed() like this:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
DateTime dateTime = formatter.withOffsetParsed().parseDateTime("2017-05-22T08:10:00.000+0300");
You have to setup time zone manually something like this:
String str = "2017-05-22T08:10:00.000+0300" ;
DateTime dateTime = new DateTime() ;
System.out.println(dateTime);
String tzName = str.substring(text.length() - 5);
DateTimeZone tz = DateTimeZoneDateTimeZone forID(str.substring(3) + ":" + str.substring(text.length() - 2))
System.out.println(dateTime.withZone(tz));
You can use the inbuilt functionalities of JDK 8 date-time API to solve this easily. The following code prints 2017-05-22T08:10+03:00.
DateTimeFormatter df = DateTimeFormatter.ISO_OFFSET_DATE_TIME ;
OffsetDateTime date1 = OffsetDateTime.parse("2017-05-22T08:10:00.000+03:00", df);
System.out.println(date1); //prints 2017-05-22T08:10+03:00
I've got a problem with the new Java Date-API, especially the java.time.DateTimeFormatter.
I'm looking for a way to add the TimeZone-Offset to a given time.
e.g.
"2016-05-27 14:22:00 UTC+2"
should be parsed to
"27.05.2016 16:22:00"
(using the pattern "dd.MM.yyyy HH:mm:ss")
This is my problematic code:
LocalDateTime time = LocalDateTime.now();
LOG.debug(time.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"));
The formatting results in a time-string which matches the given pattern, but without considering the offset of the local TimeZone.
One of the many ways of applying time zone, offset and formatting. It will help switching between Joda and Java 8 time.
Java 8 date/time api
String input = "2016-05-27 14:22:02 UTC+0200";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'Z");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss");
LocalDateTime localDateTime = parser.parse(input, LocalDateTime::from);
System.out.println(localDateTime); //2016-05-27T14:22:02
//Apply different offset on the above instant.
OffsetDateTime offsetDateTime = parser.parse(input, OffsetDateTime::from).withOffsetSameInstant(ZoneOffset.of("+07:00"));
System.out.println(offsetDateTime); //2016-05-27T19:22:02+07:00
//Apply different timezone on the above instant.
ZonedDateTime zonedDateTime = parser.parse(input, ZonedDateTime::from).withZoneSameInstant(ZoneId.of("Asia/Jakarta"));
System.out.println(zonedDateTime);// 2016-05-27T19:22:02+07:00[Asia/Jakarta]
//Apply formatting
System.out.print(formatter.format(zonedDateTime));//27.05.2016 19:22:02
Joda api
String input = "2016-05-27 14:22:02 UTC+0200";
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss 'UTC'Z");
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss");
LocalDateTime localDateTime = parser.parseLocalDateTime(input);
System.out.println(localDateTime);//2016-05-27T14:22:02.000
//Apply the above offset to the date time
DateTime offsetParsedDateTime = parser.withOffsetParsed().parseDateTime(input);
//Change to new Offset
DateTime jakartaDateTimeOffset = offsetParsedDateTime.toDateTime(DateTimeZone.forOffsetHours(7));
System.out.println(jakartaDateTimeOffset);//2016-05-27T19:22:02.000+07:00
//Change to new Zone
DateTime jakartaDateTimeZone = offsetParsedDateTime.toDateTime( DateTimeZone.forID("Asia/Jakarta") );
System.out.println(jakartaDateTimeZone);//2016-05-27T19:22:02.000+07:00
//Apply formatting
System.out.print(formatter.print(jakartaDateTimeZone ));//27.05.2016 19:22:02
Yes you can specify a offset you'd like to take in account.
You can do this in several different ways but I'll share
some piece of code that will get you going.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Local.US);
This is an example of how to create a formatting object with the set of pattern and offset.
How to convert from "2014-06-16T07:00:00.000Z" to "16-JUN-14 07:00:00" using joda time API?
The below code is throwing the exception
java.lang.IllegalArgumentException: Illegal pattern component: T
at org.joda.time.format.DateTimeFormat.parsePatternTo(DateTimeFormat.java:570)
at org.joda.time.format.DateTimeFormat.createFormatterForPattern(DateTimeFormat.java:693)
at org.joda.time.format.DateTimeFormat.forPattern(DateTimeFormat.java:181)
at com.joda.JodaTimeTest.convertJodaTimezone(JodaTimeTest.java:59)
at com.joda.JodaTimeTest.main(JodaTimeTest.java:50)
This is the code:
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-ddTHH:mm:ssZ");
DateTime dt = formatter.parseDateTime(dstDateTime.toString());
You need to enclose the literal T within single quotes. Also the milliseconds are not properly patterned. You need to include SSS for the milliseconds. Have a look at the patterns here for more info.
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Update: To format the DateTime into a String representation of your choice, you need to do this.
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
DateTime dt = formatter.parseDateTime(dstDateTime.toString()); // You get a DateTime object
// Create a new formatter with the pattern you want
DateTimeFormatter formatter2 = DateTimeFormat.forPattern("dd-MMM-yy HH:mm:ss");
String dateStringInYourFormat = formatter2.print(dt); // format the DateTime to that pattern
System.out.println(dateStringInYourFormat); // Prints 16-Jun-14 12:30:00 because of the TimeZone I'm in
Either specify the timezone yourself or your default system timezone would be taken.
You need to change
"yyyy-MM-ddTHH:mm:ssZ"
To
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
Now
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z");
DateTime dt = formatter.parseDateTime("2014-06-16T07:00:00.000Z");
System.out.println(dt);
Output:
2014-06-16T07:00:00.000+05:30
I have a string like this 2013-10-22T01:37:56. I Need to change this string into UTC Date format like this MM/dd/yyyy KK:mm:ss a. I have tried some code but it is not returning the UTC datetime.
My code is
String[] time = itsAlarmDttm.split("T");
String aFormatDate = time[0]+ " "+time[1];
String aRevisedDate = null;
try {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date dateObj = sdf.parse(aFormatDate);
aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);
} catch (ParseException e) {
itsLogger.error("Error occured in Parsing the Data Time Object: " +e.getMessage());
} catch (Exception e) {
itsLogger.error("Error occured in Data Time Objecct: " +e.getMessage());
}
I am getting the output is MM/dd/yyyy KK:mm:ss a format. But Not UTC time format.
How to solve this issue?
Try this... Worked for me and printed 10/22/2013 01:37:56 AM Ofcourse this is your code only with little modifications.
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC")); // This line converts the given date into UTC time zone
final java.util.Date dateObj = sdf.parse("2013-10-22T01:37:56");
aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);
Try to format your date with the Z or z timezone flags:
new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a Z").format(dateObj);
SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() ) );
What Time Zones?
No where in your question do you mention time zone. What time zone is implied that input string? What time zone do you want for your output? And, UTC is a time zone (or lack thereof depending on your mindset) not a string format.
ISO 8601
Your input string is in ISO 8601 format, except that it lacks an offset from UTC.
Joda-Time
Here is some example code in Joda-Time 2.3 to show you how to handle time zones. Joda-Time has built-in default formatters for parsing and generating String representations of date-time values.
String input = "2013-10-22T01:37:56";
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeUtc.withZone( DateTimeZone.forID( "America/Montreal" );
String output = dateTimeMontréal.toString();
As for generating string representations in other formats, search StackOverflow for "Joda format".
java.time
It’s about time someone provides the modern answer. The modern solution uses java.time, the modern Java date and time API. The classes SimpleDateFormat and Date used in the question and in a couple of the other answers are poorly designed and long outdated, the former in particular notoriously troublesome. TimeZone is poorly designed to. I recommend you avoid those.
ZoneId utc = ZoneId.of("Etc/UTC");
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy hh:mm:ss a zzz", Locale.ENGLISH);
String itsAlarmDttm = "2013-10-22T01:37:56";
ZonedDateTime utcDateTime = LocalDateTime.parse(itsAlarmDttm)
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(utc);
String formatterUtcDateTime = utcDateTime.format(targetFormatter);
System.out.println(formatterUtcDateTime);
When running in my time zone, Europe/Copenhagen, the output is:
10/21/2013 11:37:56 PM UTC
I have assumed that the string you got was in the default time zone of your JVM, a fragile assumption since that default setting can be changed at any time from another part of your program or another programming running in the same JVM. If you can, instead specify time zone explicitly, for example ZoneId.of("Europe/Podgorica") or ZoneId.of("Asia/Kolkata").
I am exploiting the fact that you string is in ISO 8601 format, the format the the modern classes parse as their default, that is, without any explicit formatter.
I am using a ZonedDateTime for the result date-time because it allows us to format it with UTC in the formatted string to eliminate any and all doubt. For other purposes one would typically have wanted an OffsetDateTime or an Instant instead.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
I have seen this question asked multiple times and none of the answers seem to be what i need.
I have a long type variable which has an epoch time stored in it.
What i want to do is convert it to a String
for example if the epoch time stored was for today the final string would read:
17/03/2012
How would i to this?
Look into SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.format(new Date(myTimeAsLong));
You'd create a Date from the long - that's easy:
Date date = new Date(epochTime);
Note that epochTime here ought to be in milliseconds since the epoch - if you've got seconds since the epoch, multiply by 1000.
Then you'd create a SimpleDateFormat specifying the relevant pattern, culture and time zone. For example:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
format.setTimeZone(...);
Then use that to format the date to a string:
String text = format.format(date);
Date date = new Date(String);
this is deprecated.
solution
Date date = new Date(1406178443 * 1000L);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
make sure multiply by 1000L
If the method should be portable, better use the default (local time) TimeZone.getDefault():
String epochToIso8601(long time) {
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
sdf.setTimeZone(TimeZone.getDefault());
return sdf.format(new Date(time * 1000));
}
try this
Date date = new Date(1476126532838L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
format.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));//your zone
formatted = format.format(date);
System.out.println(formatted);
Joda-Time
If by epoch time you meant a count of milliseconds since first moment of 1970 in UTC, then here is some example code using the Joda-Time library…
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( yourMilliseconds, timeZone );
String output = DateTimeFormat.forStyle( "S-" ).withLocale( Locale.CANADA_FRENCH ).print( dateTime );
Other Epochs
That definition of epoch is common because of its use within Unix. But be aware that at least a couple dozen epoch definitions are used by various computer systems.
Time for someone to provide the modern answer (valid and recommended since 2014).
java.time
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG).withLocale(Locale.US);
String facebookTime = "1548410106047";
long fbt = Long.parseLong(facebookTime);
ZonedDateTime dateTime = Instant.ofEpochMilli(fbt).atZone(ZoneId.of("America/Indiana/Knox"));
System.out.println(dateTime.format(formatter));
The output is:
January 25, 2019 at 3:55:06 AM CST
If you wanted only the date and in a shorter format, use for example
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.US);
1/25/19
Note how the snippet allows you to specify time zone, language (locale) and how long or short of a format you want.
Links
Oracle tutorial: Date Time explaining how to use java.time.
My example string was taken from this duplicate question
Try this...
sample Epoch timestamp is 1414492391238
Method:
public static String GetHumanReadableDate(long epochSec, String dateFormatStr) {
Date date = new Date(epochSec * 1000);
SimpleDateFormat format = new SimpleDateFormat(dateFormatStr,
Locale.getDefault());
return format.format(date);
}
Usability:
long timestamp = Long.parseLong(engTime) / 1000;
String engTime_ = GetHumanReadableDate(timestamp, "dd-MM-yyyy HH:mm:ss aa");
Result:
28-10-2014 16:03:11 pm
You need to be aware that epoch time in java is in milliseconds, while what you are converting may be in seconds. Ensure that both sides of the conversions are in milliseconds, and then you can fetch the date parameters from the Date object.
ArLiteDTMConv Utility help converting EPOUCH-UNIX Date-Time values, Form EPOUCH-UNIX-To-Date-format and Vise-Versa. You can set the result to a variable and then use the variable in your script or when passing as parameter or introduce in any DB criteria for both Window and Linux. (Download a zip file on this link)