Possible Solution:Convert Java Date into another Time as Date format
I went through it but does not get my answer.
I have a string "2013-07-17T03:58:00.000Z" and I want to convert it into date of the same form which we get while making a new Date().Date d=new Date();
The time should be in IST Zone - Asia/Kolkata
Thus the date for the string above should be
Wed Jul 17 12:05:16 IST 2013 //Whatever Time as per Indian Standard GMT+0530
String s="2013-07-17T03:58:00.000Z";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
TimeZone tx=TimeZone.getTimeZone("Asia/Kolkata");
formatter.setTimeZone(tx);
d= (Date)formatter.parse(s);
Use calendar for timezones.
TimeZone tz = TimeZone.getTimeZone("Asia/Calcutta");
Calendar cal = Calendar.getInstance(tz);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
sdf.setCalendar(cal);
cal.setTime(sdf.parse("2013-07-17T03:58:00.000Z"));
Date date = cal.getTime();
For this however I'd recommend Joda Time as it has better functions for this situation. For JodaTime you can do something like this:
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTime dt = dtf.parseDateTime("2013-07-17T03:58:00.000Z");
Date date = dt.toDate();
A Date doesn't have any time zone. If you want to know what the string representation of the date is in the indian time zone, then use another SimpleDateFormat, with its timezone set to Indian Standard, and format the date with this new SimpleDateFormat.
EDIT: code sample:
String s = "2013-07-17T03:58:00.000Z";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date d = formatter.parse(s);
System.out.println("Formatted Date in current time zone = " + formatter.format(d));
TimeZone tx=TimeZone.getTimeZone("Asia/Calcutta");
formatter.setTimeZone(tx);
System.out.println("Formatted date in IST = " + formatter.format(d));
Output (current time zone is Paris - GMT+2):
Formatted Date in current time zone = 2013-07-17T05:58:00.000+02
Formatted date in IST = 2013-07-17T09:28:00.000+05
java.time
I should like to provide the modern answer. And give you a suggestion: rather than reproducing what Date.toString() would have given you, better to use the built-in format for users in the relevant locale:
String isoString = "2013-07-17T03:58:00.000Z";
String humanReadable = Instant.parse(isoString)
.atZone(userTimeZone)
.format(localizedFormatter);
System.out.println(humanReadable);
On my computer this prints
17 July 2013 at 09.28.00 IST
My snippet uses a couple of constants
private static final ZoneId userTimeZone = ZoneId.of("Asia/Kolkata");
private static final DateTimeFormatter localizedFormatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.getDefault(Locale.Category.FORMAT));
The withLocale call is redundant when we just pass the default format locale. I put it in so you have a place to provide an explicit locale, should your users require a different one. It also has the nice advantage of making explicit that the result depends on locale, in case someone reading your code didn’t think of that.
I am using java.time, the modern Java date and time API. It is so much nicer to work with than the outdated Date, TimeZone and the notoriously troublesome DateFormat and SimpleDateFormat. Your string conforms to the ISO 8601 standard, a format that the modern classes parse as their default, that is, without any explicit formatter.
Same format as Date gave you
Of course you can have the same format as the old-fashioned Date would have given you if you so require. Just substitute the formatter above with this one:
private static final DateTimeFormatter asUtilDateFormatter
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
Now we get:
Wed Jul 17 09:28:00 IST 2013
Link to tutorial
Read more about using java.time in the Oracle tutorial and/or find other resources out there.
Related
I am trying to get time (HH:MM) from below code in IST format but it still display UTC date, time.
Please help.
public static void main (String args[]) throws ParseException {
String date = "2021-07-05T14:17:00.000Z";
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
String timezoneID = timeZone.getID();
// Convert to System format from UTC
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date actualDate = format1.parse(date);
format1.setTimeZone(TimeZone.getTimeZone(timezoneID));
String date1 = format1.format(actualDate);
String time = date1.substring(11, 16);
String timezoneValue = TimeZone.getTimeZone(timezoneID).getDisplayName(false, TimeZone.SHORT);
String finalTime = time + " " + timezoneValue;
System.out.print(finalTime);
}
java.time
I strongly recommend that you use java.time, the modern Java date and time API, for your date and time work. Then your task becomes pretty simple. Rather than a formatter for your input format I want to define a formatter for your desired time format:
private static final DateTimeFormatter TIME_FORMATTER
= DateTimeFormatter.ofPattern("HH:mm zzz", Locale.ENGLISH);
Now the operation goes in these few lines:
String date = "2021-07-05T14:17:00.000Z";
String finalTime = Instant.parse(date)
.atZone(ZoneId.systemDefault())
.format(TIME_FORMATTER);
System.out.println(finalTime);
Output when I ran in Europe/Dublin time zone:
15:17 IST
Here IST is for Irish Summer Time. IST has several meanings, and I wasn’t sure which one you intended. Also many of the other popular time zone abbreviations are ambiguous. IST may also mean Israel Standard Time, but not here, since Israel uses Israel Daylight Time or IDT at this time of year. One other interpretation is India Standard Time used in India and Sri Lanka, So let’s try running the code in Asia/Kolkata time zone.
19:47 IST
I am exploiting the fact that your string is in ISO 8601 format, the format that the classes of java.time parse and also print as their default, that is, without any specified formatter.
What went wrong in your code?
Your bug is here:
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
You must never hardcode Z as a literal in your format pattern, which is what you are doing when enclosing it in single quotes. The Z is a UTC offset and needs to be parsed as such so that Java knows that your date and time are in UTC (which is what Z means). When you hardcode the Z, SimpleDateFormat understands the date and time to be in the default time zone of the JVM. So when afterward you try to convert into that time zone, the time of day is not changed. You’re converting into the time zone you already had. It’s a no-op.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Time Zone Abbreviations – Worldwide List
You are parsing the date using your default TimeZone, not UTC.
You never called format1.setTimeZone before parsing. A DateFormat uses the default timezone unless you set it to something else.
Let’s look at each line of your code:
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
That is getting the default TimeZone. You don’t need a Calendar object for that; just call TimeZone.getDefault().
String timezoneID = timeZone.getID();
There is no reason to call that. You already have a TimeZone object. Converting it to a string ID and back to a TimeZone is a pointless round-trip operation. So, you should remove all uses of timezoneID.
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
That is the problem. The DateFormat doesn’t treat the 'Z' as anything special; it’s just a literal character which the DateFormat knows not to parse.
You need to actually tell the DateFormat that it’s parsing a UTC time:
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
TimeZone utc = TimeZone.getTimeZone(ZoneOffset.UTC);
format1.setTimeZone(utc);
Date actualDate = format1.parse(date);
Instead of cutting out pieces of a formatted string, make a new DateFormat that does exactly what you want:
DateFormat timeFormat = new SimpleDateFormat("HH:mm z");
String finalTime = timeFormat.format(actualDate);
Since a SimpleDateFormat always uses the default TimeZone when it is created, there is no need to call this format object’s setTimeZone method.
I should mention that the java.time and java.time.format packages are much better for working with dates and times:
String date = "2021-07-05T14:17:00.000Z";
Instant instant = Instant.parse(date);
ZonedDateTime utcDateTime = instant.atZone(ZoneOffset.UTC);
ZonedDateTime istDateTime =
utcDateTime.withZoneSameInstant(ZoneId.systemDefault());
String finalTime = String.format("%tR %<tZ", istDateTime);
// Or:
// String finalTime = istDateTime.toLocalTime() + " "
// + itsDateTime.getZone().getDisplayName(
// TextStyle.SHORT, Locale.getDefault());
format1.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
is what you need since the 3-letter zone names are really deprecated. Plus:
String timezoneValue = format1.getTimeZone().getDisplayName(false, TimeZone.SHORT);
The method Calendar.getInstance() gets a calendar using the default time zone and locale - UTC±00:00.
Use "IST" instead of timeZone.getID().
Exemple:
String date="2021-07-05T14:17:00.000Z";
Calendar now = Calendar.getInstance();
TimeZone timeZone = now.getTimeZone();
String timezoneID = "IST"; // <<<<<
// Convert to System format from UTC
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date actualDate = format1.parse(date);
format1.setTimeZone(TimeZone.getTimeZone(timezoneID));
String date1 = format1.format(actualDate);
String time = date1.substring(11, 16);
String timezoneValue = TimeZone.getTimeZone(timezoneID).getDisplayName(false, TimeZone.SHORT);
String finalTime = time + " " + timezoneValue;
System.out.print(finalTime);
I have a function where I need to grab the current date, set to another time zone, and return that converted/formatted date as a Date object. I have code that works, however, the Date object does not set to the newly converted date, it returns the current date.
Here is the code:
public static Date getCurrentLocalDateTime() {
Calendar currentdate = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TimeZone obj = TimeZone.getTimeZone("America/Denver");
formatter.setTimeZone(obj);
Logger.info("Local:: " + currentdate.getTime());
String formattedDate = formatter.format(currentdate.getTime());
Logger.info("America/Denver:: "+ formattedDate);
Date finalDate = null;
try {
finalDate = formatter.parse(formattedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Logger.info("finalDate:: " + finalDate);
return finalDate;
}
From the examples I have reviewed and tried, this should work correctly. One of the issues is that I need to return the Date object so it works with the current code.
The output looks like:
2017-07-03 17:08:24,499 [INFO] from application in application-akka.actor.default-dispatcher-3 -
Local:: Mon Jul 03 17:08:24 UTC 2017
2017-07-03 17:08:24,501 [INFO] from application in application-akka.actor.default-dispatcher-3 -
America/Denver:: 2017-07-03 11:08:24
2017-07-03 17:08:24,502 [INFO] from application in application-akka.actor.default-dispatcher-3 -
finalDate:: Mon Jul 03 17:08:24 UTC 2017
As you can see, it formats the date correctly to the Mountain Time Zone, but then sets it back to the Calendar time.
EDIT --- Code solution:
public static Date getCurrentLocalDateTime() {
Calendar currentdate = Calendar.getInstance();
ZonedDateTime converted = currentdate.toInstant().atZone(ZoneId.of("America/Denver"))
.withZoneSameLocal(ZoneOffset.UTC);
Date finalDate = Date.from(converted.toInstant());
return finalDate;
}
A java.util.Date object has no timezone information. It has only a long value, which is the number of milliseconds from 1970-01-01T00:00:00Z (also known as "unix epoch" or just "epoch"). This value is absolutely independent of timezone (you can say "it's in UTC" as well).
When you call Logger.info("finalDate:: " + finalDate);, it calls the toString() method of java.util.Date, and this method uses the system's default timezone behind the scenes, giving the impression that the date object itself has a timezone - but it doesn't.
Check the values of finalDate.getTime() and currentdate.getTimeInMillis(), you'll see they are almost the same - "almost" because the SimpleDateFormat doesn't have the fraction of seconds, so you're losing the milliseconds precision (format method creates a String without the milliseconds, and the parse method sets it to zero when the field is not present). If I change the formatter to this, though:
// using ".SSS" to don't lose milliseconds when formatting
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
The output is:
Local:: Mon Jul 03 17:34:34 UTC 2017
America/Denver:: 2017-07-03 11:34:34.508
finalDate:: Mon Jul 03 17:34:34 UTC 2017
And both finalDate.getTime() and currentdate.getTimeInMillis() will have exactly the same values (Note that Date.toString() doesn't print the milliseconds, so you can't know what's their value - only by comparing getTime() values you know if they are the same).
Conclusion: just change your formatter to use the milliseconds (.SSS) and parsing/formatting will work. The fact that it shows the dates in another timezone is an implementation detail (toString() method uses system's default timezone), but the milliseconds value is correct.
If you want to get 11h at UTC, you must create another formatter and set its timezone to UTC:
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
finalDate = parser.parse(formattedDate);
Then, finalDate's time will have the value of 11h at UTC:
finalDate:: Mon Jul 03 11:34:34 UTC 2017
New Java Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
To do what you need, you can use a ZonedDateTime (a date and time + a timezone) and convert to another timezone keeping the same date/time values:
// current date/time in Denver
ZonedDateTime denverNow = ZonedDateTime.now(ZoneId.of("America/Denver"));
// convert to UTC, but keeping the same date/time values (like 11:34)
ZonedDateTime converted = denverNow.withZoneSameLocal(ZoneOffset.UTC);
System.out.println(converted); // 2017-07-03T11:34:34.508Z
The output will be:
2017-07-03T11:34:34.508Z
If you want a different format, use a DateTimeFormatter:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// pattern for day/hour
.appendPattern("EEE MMM dd HH:mm:ss ")
// UTC offset
.appendOffset("+HHMM", "UTC")
// year
.appendPattern(" yyyy")
// create formatter
.toFormatter(Locale.ENGLISH);
System.out.println(fmt.format(converted));
The output will be:
Mon Jul 03 11:34:34 UTC 2017
If you still need to use java.util.Date, you can easily convert from/to the new API.
In Java >= 8:
// convert your Calendar object to ZonedDateTime
converted = currentdate.toInstant()
.atZone(ZoneId.of("America/Denver"))
.withZoneSameLocal(ZoneOffset.UTC);
// converted is equals to 2017-07-03T11:34:34.508Z
// from ZonedDateTime to Date and Calendar (date will be 11:34 UTC)
Date d = Date.from(converted.toInstant());
Calendar cal = Calendar.getInstance();
cal.setTime(d);
// to get a Date that corresponds to 11:34 in Denver
Date d = Date.from(converted.withZoneSameLocal(ZoneId.of("America/Denver")).toInstant());
Calendar cal = Calendar.getInstance();
cal.setTime(d);
In Java <= 7 (ThreeTen Backport), you can use the org.threeten.bp.DateTimeUtils class:
// convert Calendar to ZonedDateTime
converted = DateTimeUtils.toInstant(currentdate)
.atZone(ZoneId.of("America/Denver"))
.withZoneSameLocal(ZoneOffset.UTC);
// converted is equals to 2017-07-03T11:34:34.508Z
// convert ZonedDateTime to Date (date will be 11:34 UTC)
Date d = DateTimeUtils.toDate(converted.toInstant());
Calendar c = DateTimeUtils.toGregorianCalendar(converted);
// to get a Date that corresponds to 11:34 in Denver
Date d = DateTimeUtils.toDate(converted.withZoneSameLocal(ZoneId.of("America/Denver")).toInstant());
Calendar c = DateTimeUtils.toGregorianCalendar(converted.withZoneSameLocal(ZoneId.of("America/Denver")));
Is there any way to use the following simpleDateFormat:
final SimpleDateFormat simpleDateFormatHour = new SimpleDateFormat("HH:mm:ss z");
and when invoking:
simpleDateFormat.parse("12:32:21 JST");
to return current date on the Date object?
For these example, it will return:
Thu Jan 01 05:32:21 EET 1970
and not:
<<today>> 05:32:21 EET <<currentYear>>
as I need.
No, SimpleDateFormat needs explicity the date in the input string. If you're using Java 8, you can go with a LocalDateTime:
LocalDateTime localDateTime = LocalDate.now().atTime(5, 32, 21);
If you want to include a time-zone, you can use ZonedDateTime.
Construct another SimpleDateFormat to print today's date:
String today = new SimpleDateFormat("yyyy/MM/dd").print(new Date());
(Be careful here: you might want to set the time zone on the SimpleDateFormat, as "today" is different in different time zones).
Update the date format to include year, month and day:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
And then prepend the date string with the date you want:
simpleDateFormat.parse(today + " " + "12:32:21 JST");
A better solution using flexible default values (today instead of 1970-01-01) would be in Java-8 with the new built-in date-time-library located in package java.time:
String input = "12:32:21 JST";
String pattern = "HH:mm:ss z";
LocalDate today = LocalDate.now(ZoneId.of("Asia/Tokyo"));
DateTimeFormatter dtf =
new DateTimeFormatterBuilder().parseDefaulting(ChronoField.YEAR, today.getYear())
.parseDefaulting(ChronoField.MONTH_OF_YEAR, today.getMonthValue()).parseDefaulting(
ChronoField.DAY_OF_MONTH,
today.getDayOfMonth()
).appendPattern(pattern).toFormatter(Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(input, dtf);
System.out.println(zdt); // 2016-12-23T12:32:21+09:00[Asia/Tokyo]
However, I still see a small bug related to the fact that this code makes a hardwired assumption about the used zone BEFORE parsing the real zone so please handle with care. Keep in mind that the current date depends on the zone. But maybe you only need to handle a scenario where just the Japan time is used by users.
Hint: You can also parse in two steps. First step with any kind of fixed default date in order to get the zone information of the text to be parsed. And then you can use this zone information for suggested solution above. An awkward but safe procedure.
You can use this code if you want to change only the year and the day
final SimpleDateFormat simpleDateFormatHour = new SimpleDateFormat("HH:mm:ss z");
Date date = simpleDateFormatHour.parse("12:32:21 JST");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
calendar.set(Calendar.DAY_OF_YEAR, Calendar.getInstance().get(Calendar.DAY_OF_YEAR));
date = calendar.getTime();
Requirement : I want to get only TimeZone field from new Date(), As of now from new Date() ,I am getting result as
Wed Jul 23 19:37:20 GMT+05:30 2014,But I want only GMT+05:30,Is there any way to get only this?
PS:I dont want to use split for getting timezone field.because this is my final option for achieving above requirement.
You should use the Calendar class and likely, the implementation GregorianCalendar. A lot of the Date functions have been deprecated in favor of using Calendar. Java 8 has the Clock API, but I'll assume Java 7 here.
That way you can do this:
Calendar calendar = new GregorianCalendar();
TimeZone tz = calendar.getTimeZone();
And work from there.
Assuming you have to work with a String input you can do something like this:
// format : dow mon dd hh:mm:ss zzz yyyy
String date = "Wed Jul 23 19:37:20 GMT+05:30 2014";
Pattern pattern = Pattern
.compile("^\\w{3}\\s\\w{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s?(.*)\\s\\d{4}$");
Matcher matcher = pattern.matcher(date);
if (matcher.matches()) {
String timezone = matcher.group(1);
// beware : according to the Date.toString() documentation the timezone
// value can be empty
System.out.println(timezone);
} else {
System.out.println("doesn't match!");
}
import java.util package and use GregorianCalendar method.
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
System.out.println("Current time is "+hour+" : "+minute+" : "+second);
Don't use Date and Time class of java.util package as their methods are deprecated means they may not be supported in future versions of JDK.
Generate String With Offset But No Date and No Time
Your question is inaccurate. A java.util.Date has no time zone (assumes to always be in UTC). The JVM's time zone is applied in the object' toString method and in other formatting code that generates a String representation. Therein lies your solution: use a date-time formatter that generates a String containing only the offset from UTC without the date or the time-of-day portions.
Avoid java.util.Date & .Calendar
Avoid using the bundled java.util.Date and .Calendar classes as they are notoriously troublesome. Instead use either Joda-Time or the new java.time package. Both support time zones as part of a date-time object.
Joda-Time
Here is how to generate a String representation of a DateTime in Joda-Time 2.3.
DateTime dateTime = new DateTime( DateTimeZone.forID( "Asia/Kolkata" ) );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "ZZ" );
String offset = formatter.print( dateTime ); // generates: +05:30
In Joda-Time 2.3 you can ask a DateTime object for its assigned time zone as an object. You may then interrogate the DateTimeZone object.
DateTime dateTime = new DateTime( DateTimeZone.forID( "Asia/Kolkata" ) );
DateTimeZone timeZone = dateTime.getZone();
String id = timeZone.getID();
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)