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
Related
I have a datetime-string WITHOUT a specified timezone.
But I want to parse it with ZonedDateTime to give it a timezone-meaning in the act of parsing.
This code is working but uses LocalDateTime for parsing - and then convert it to ZonedDateTime with giving it a timezone-meaning.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern ("yyyyMMddHHmm");
String tmstr = "201810110907";
LocalDateTime tmp = LocalDateTime.parse (tnstr,dtf);
ZonedDateTime mytime = ZonedDateTime.of (tmp, ZoneId.of ("UTC"));
Is there a way I can parse it directly with ZonedDateTime?
I have tried this, but it was not working.
mytime = mytime.withZoneSameInstant(ZoneId.of("UTC")).parse(str,dtf);
You may specify a default time zone on the formatter:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmm")
.withZone(ZoneId.of("UTC"));
String tmstr = "201810110907";
ZonedDateTime mytime = ZonedDateTime.parse(tmstr, dtf);
System.out.println(mytime);
Output:
2018-10-11T09:07Z[UTC]
Bonus tip: Rather than ZoneId.of("UTC") it’s usually nicer to use ZoneOffset.UTC. If you accept the output being printed as 2018-10-11T09:07Z instead (Z meaning UTC).
I have a timestamp column in oracle table. While storing time I store it in UTC in this column. For retrieving this time stamp I am using Spring's JdbcTemplate while returns object of type TimeStamp.
I want to get date time string in "dd-MM-YYYY HH:mm:ss" format in current time zone. In order to achieve that I am trying following code:
new LocalDateTime(<retrieved TimeStamp>, <current user DateTimeZone>).toString("yyyy-MM-dd HH:mm:ss")
Both LocalDateTime and DateTimeZone from Joda library.
How ever this isn't working as per expected. Instead of current user's time zone above code gives me date time string in UTC only.
What am I missing?
I think your application is using java.util.Date which has no time zone information, the toString usage applies the JVM’s current default time zone when creating a string.
You can adjust the timezone instant by (Using Joda Library)
ZonedDateTime Tokyo = ZonedDateTime.ofInstant (instant,zoneIdTokyo) ;
Or implement zones
DateTimeZone zone = DateTimeZone.forID("Asia/Tokyo");
You are using
LocalDateTime which is immutable class representing a local date and time (no time zone)
EDIT - You can try this
(I haven't tested it)
DateTime udate = new DateTime("2016-05-01T20:10:04", DateTimeZone.UTC);
System.out.println(udate);
DateTime zone = udate.plusMillis(10000)
.withZone(DateTimeZone.forID("Asia/Kolkata"));
System.out.println(zone);
Add utc calendar when fetching the timestamp from database, so the jdbc driver can use this calendar timezone instead of default system timezone.
//Assign utc calendar
Calendar utc= Calendar.getInstance();
utc.setTimeZone(TimeZone.getTimeZone("UTC"));
Timestamp timestamp = rs.getTimestamp("timestampcolumn", utc);
//Convert to client date time
DateTime dateTime = new DateTime(timestamp.getTime(), DateTimeZone.forID("Asia/Kolkata"));
//Format
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-YYYY HH:mm:ss");
//Change to client wall clock time
LocalDateTime localDateTime = dateTime.toLocalDateTime();
String formattedlocalDateTime = formatter.print(localDateTime)
Example
String utcTime = "2016-06-17 14:22:02Z";
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZ");
DateTime dateTime = parser.parseDateTime(utcTime).withZone(DateTimeZone.forID("Asia/Kolkata"));
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-YYYY HH:mm:ss");
System.out.println(dateTime);
LocalDateTime localDateTime = dateTime.toLocalDateTime();
String formattedlocalDateTime = formatter.print(localDateTime);
System.out.println(formattedlocalDateTime);
I have a time with string type like: "2015-01-05 17:00" and ZoneId is "Australia/Sydney".
How can I convert this time information to the corresponding to UTC time using Java 8 datetime API?
Also need to considering DST stuff.
You are looking for ZonedDateTime class in Java8 - a complete date-time with time-zone and resolved offset from UTC/Greenwich. In terms of design, this class should be viewed primarily as the combination of a LocalDateTime and a ZoneId. The ZoneOffset is a vital, but secondary, piece of information, used to ensure that the class represents an instant, especially during a daylight savings overlap.
For example:
ZoneId australia = ZoneId.of("Australia/Sydney");
String str = "2015-01-05 17:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime localtDateAndTime = LocalDateTime.parse(str, formatter);
ZonedDateTime dateAndTimeInSydney = ZonedDateTime.of(localtDateAndTime, australia );
System.out.println("Current date and time in a particular timezone : " + dateAndTimeInSydney);
ZonedDateTime utcDate = dateAndTimeInSydney.withZoneSameInstant(ZoneOffset.UTC);
System.out.println("Current date and time in UTC : " + utcDate);
An alternative to the existing answer is to setup the formatter with the appropriate time zone:
String input = "2015-01-05 17:00";
ZoneId zone = ZoneId.of("Australia/Sydney");
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(zone);
ZonedDateTime utc = ZonedDateTime.parse(input, fmt).withZoneSameInstant(UTC);
Since you want to interact with a database, you may need a java.sql.Timestamp, in which case you don't need to explicitly convert to a UTC time but can use an Instant instead:
ZonedDateTime zdt = ZonedDateTime.parse(input, fmt);
Timestamp sqlTs = Timestamp.from(zdt.toInstant());
**// Refactored Logic**
ZoneId australia = ZoneId.of("Australia/Sydney");
ZoneId utcZoneID= ZoneId.of("Etc/UTC");
String ausTime = "2015-01-05 17:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//converting in datetime of java8
LocalDateTime ausDateAndTime = LocalDateTime.parse(ausTime, formatter);
// DateTime With Zone
ZonedDateTime utcDateAndTime = ausDateAndTime.atZone(utcZoneID);
// output - 2015-01-05T17:00Z[Etc/UTC]
// With Formating DateTime
String utcDateTime = utcDateAndTime.format(formatter);
// output - 2015-01-05 17:00
if I have a string date:
2013-11-14T00:00:00.000
What date format can I use to create a date with the offset?
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
dateFormat.setTimeZone(TimeZone.getDefault());
Date date = dateFormat.parse(myDate);
The above gives an unparsable date error.
"yyyy-MM-dd'T'HH:mm:ss.SSS"
Use SSS for milliseconds and remove Z as the date string does not have a time zone.
If you intend to print/log the date in another format (with a custom time zone, for example), you will have to use another instance of DateFormat:
"yyyy-MM-dd'T'HH:mm:ss.SSS" // to parse the date string
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" // to format the date object
The .000 on the end is not a time zone designation; it looks like milliseconds. Try replacing the Z time zone designation with SSS for milliseconds.
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
your supplied 2013-11-14T00:00:00.000 is not specified with the above pattern: "yyyy-MM-dd'T'HH:mm:ss.SSS Z" as sample valid input for this pattern would be:
2013-11-14T00:00:00.000 -0700
Either drop the Z or pass a string as the mentioned sample.
FYI, here is that same kind of code using Joda-Time 2.3.
Joda-Time uses that kind of ISO 8601 format as its default. No need for a formatter to parse that string. Merely pass the string to a DateTime constructor. The constructor automatically invokes a built-in ISO formatter.
String input = "2013-11-14T00:00:00.000";
// Specify a time zone rather than rely on default.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( input, timeZone );
System.out.println( "dateTime: " + dateTime );
When run…
dateTime: 2013-11-14T00:00:00.000+01:00
If you need a java.util.Date for use with other classes, convert from Joda-Time.
java.util.Date date = dateTime.toDate();
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)