Converting datastamps to epoch (including GMT or UTC) - java

I am looking to convert timestamps into epoch (number of millisconds since 1970) - java.
I want an extensive parser - that supports both GMT/UTC and perheps other format.
For example:
new DateStamp("yyyy-MM-DD HH:mm:ss,ccc o").parse("2012-09-01 13:44:21222 GMT+2")
That is, I don't want to put in the actual format my self (GMT/UTC), but rather leave that for the parser.

You could use SimpleDateFormat:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,S Z");
Date date = df.parse("2012-09-01 13:44:21,222 GMT+2:00");
long time = date.getTime(); // milliseconds since epoch
For ISO 8601 Time zone:
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,S Z");
Date date = df.parse("2012-09-01 13:44:21,222 +02");

Related

SimpleDate format is not converting time to IST

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);

Convert timestamp to time gives the wrong time

I don't know what I'm doing wrong here. I've got a timestamp (long), and am trying to change it to a readable format.
Here's the timestamp:
1404162530517
When I verify the time using epoch converter, it says it is 5:08PM (correct)
When I try and use my code to parse it, it says 10:21PM (wrong)
Here's the code that doesn't work:
long unixSeconds = Long.parseLong(tstamp);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEE MMM dd", Locale.ENGLISH);
formattedDate = dateFormat.format(date);
SimpleDateFormat timeFormat = new SimpleDateFormat(
"hh:mma ", Locale.ENGLISH);
timeDate = timeFormat.format(date);
System.out.println(tstamp);
System.out.println(timeDate);
How can I fix this?
Okay, so your in the timezone EDT. However, the Unix timestamp is counted from the Unix epoch in UTC. In other words, you are 5 hours behind UTC, and so the timestamp is 5 hours off since it's counting from midnight 1970 in UTC.
So how do you fix this? In your first SimpleDateFormat, put that the input timezone is UTC. That should convert UTC to your time (EDT):
SimpleDateFormat dateFormat = new SimpleDateFormat(
"EEE MMM dd", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
formattedDate = dateFormat.format(date);
Have you tried dividing your timestamp by 1000? by default the correct timestamp is only 10 digits I guess.

Converting String in ISO8601 T-Z format to Date

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.

Java convert date to EST timezone to respecting DST

I want to get the current date converted to America/Montreal timezone. I'm doing it like this:
Date date = new Date();
TimeZone timeZone = TimeZone.getTimeZone ("America/Montreal");
Calendar cal = new GregorianCalendar(timeZone);
cal.setTime(date);
String whatIWant = "" + cal.get(Calendar.HOUR_OF_DAY) + ':'+
cal.get(Calendar.MINUTE)+ ':'+ cal.get(Calendar.SECOND);
log.info(whatIWant);
The conversion is just fine but I was wondering how robust this code is. What will happen when in no daylight saving?
That code is fine. Java automatically takes winter time or summer time into account.
You could also do this by using a DateFormat object to convert the date to a string, setting the desired time zone on the DateFormat object:
Date date = new Date();
DateFormat df = new SimpleDateFormat("HH:mm:ss");
// Tell the DateFormat that you want the time in this timezone
df.setTimeZone(TimeZone.getTimeZone("America/Montreal"));
String whatIWant = df.format(date);

Converting Epoch time to date string

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)

Categories

Resources