Convert "2020-10-31T00:00:00Z" String Date to long [duplicate] - java

This question already has answers here:
Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST
(9 answers)
How to validate the DateTime string format "2018-01-22T18:23:00.000Z" in Java?
(2 answers)
parsing date/time to localtimezone
(2 answers)
Closed 3 years ago.
I am having Input Date as "2020-10-31T00:00:00Z". i want to parse this Date to get Long milliseconds.
Note: Converted milliseconds should be in Sydney Time (ie GMT+11).
FYI,
public static long RegoExpiryDateFormatter(String regoExpiryDate)
{
long epoch = 0;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
df.setTimeZone(TimeZone.getTimeZone("GMT+11"));
Date date;
try {
date = df.parse(regoExpiryDate);
epoch = date.getTime();
} catch (ParseException e) {
System.out.println("Exception is:" + e.getMessage());
e.printStackTrace();
}
System.out.println("Converted regoExpiryDate Timestamp*************** " + epoch);
return epoch;
}
Output: 1604062800000 which gives Date as 30/10/2019 by using Epoch Converter, but in input i'm passing 31st as Date.
Can anyone please clarify this?

By doing df.setTimeZone(TimeZone.getTimeZone("GMT+11"));, you are asking the date formatter to interpret your string in the GMT+11 time zone. However, your string shouldn't be interpreted in that timezone. See that Z in the string? That stands for the GMT time zone, so you should have done this instead:
df.setTimeZone(TimeZone.getTimeZone("GMT"));
In fact, your string is in the ISO 8601 format for an Instant (or a "point in time", if you prefer). Therefore, you could just parse it with Instant.parse, and get the number of milliseconds with toEpochMilli:
System.out.println(Instant.parse("2020-10-31T00:00:00Z").toEpochMilli());
// prints 1604102400000
Warning: you shouldn't really use SimpleDateFormat anymore if the Java 8 APIs (i.e. Instant and such) are available. Even if they are not, you should use NodaTime or something like that.

Related

Bad format date with dd-MMM-yy [duplicate]

This question already has answers here:
Java - Unparseable date
(3 answers)
java.time.format.DateTimeParseException for dd-MMM-yyyy format [duplicate]
(1 answer)
Closed 2 years ago.
I have the following input String "30-JUL-21" for my date, and I want to convert to an Instant.
But I cannot find the correct solution... do you have an idea?
I already tried with
SimpleDateFormat sdfmt2 = new SimpleDateFormat("dd-MMM-yy");
result = sdfmt2.parse(source).toInstant();
but it doesn't work properly.
my code:
String src = "30-JUL-21";
Instant result = null;
if (!StringUtils.isEmpty(src)) {
try {
SimpleDateFormat sdfmt2= new SimpleDateFormat("dd-MMM-yy");
result = sdfmt2.parse(src).toInstant();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
You could build a DateTimeFormatter that parses case insensitively and uses an English Locale along with a matching pattern, because your representation of the month is not parseable by a pattern only.
See the following example where every step is done explicitly and where UTC is used as time zone. Alternatively, you can use the time zone of the system by replacing ZoneId.of("UTC") with ZoneId.systemDefault(), which will affect the output, of course, if the system's time zone is not UTC. I chose UTC here to have comparable output since I don't know your time zone (do you?):
public static void main(String[] args) {
// example input
String source = "30-JUL-21";
// create a formatter that parses case-insensitively using a matching pattern
DateTimeFormatter caseInsensitiveDtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("dd-MMM-uu")
.toFormatter(Locale.ENGLISH);
// parse the String using the previously defined formatter
LocalDate localDate = LocalDate.parse(source, caseInsensitiveDtf);
// print this intermediate result
System.out.println(localDate);
// build up a datetime by taking the start of the day and adding a time zone
ZonedDateTime zdt = localDate.atStartOfDay(ZoneId.of("UTC"));
// print that intermediate result, too
System.out.println(zdt);
// then simply convert it to an Instant
Instant instant = zdt.toInstant();
// and print the epoch millis of it
System.out.println(instant.toEpochMilli());
}
The output of it is this (last print uses the resulting Instant):
2021-07-30
2021-07-30T00:00Z[UTC]
1627603200000

Java 7 Parse DateTime with Seconds to 7 decimal places [duplicate]

This question already has answers here:
Java date parsing with microsecond or nanosecond accuracy
(3 answers)
Closed 4 years ago.
I have to parse a date time String being sent over json - using Java 7, with the date time being in this format :
2016-04-26T11:35:30.0543787Z
The problem I'm having is with the extra decimals in the seconds - I can parse it if it is only to 3 decimal places e.g. milliseconds.
I can parse the value using SimpleDateFormat and the format string
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" but this gives an incorrect value.
Any help would be appreciated!
Since you are not bother about the precision of the milliseconds, we can remove the decimals from the seconds.
**NB:**And the output would depend on the current timezone of your server/machine. That's why the you felt like the output is different from what you expected.
String time = "2016-04-26T11:35:30.0543787Z";
int l = time.lastIndexOf('.');
time = time.substring(0, l);
time = time+"Z";
System.out.println(time);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
Date date = dateFormat.parse(time.replaceAll("Z$", "+0000"));
System.out.println(date);
System.out.println("time zone : " + TimeZone.getDefault().getID());
System.out.println(dateFormat.format(date));
} catch (ParseException e) {
e.printStackTrace();
}

SimpleDateFormat adds 1 hour when convert UTC time to Australia time zone [duplicate]

This question already has answers here:
Java SimpleDateFormat parse result off by one hour (and yes, I set the time zone)
(2 answers)
Closed 6 years ago.
I have used following code to convert UTC time to device current time zone time. It works fine on Indian Standard Time (IST). But it adds 1 hour additionally when device time zone is Sydney, Australia.
For example, I give UTC time like 2016-10-10T09:10:00 and it is converts as 8:10 PM, but actually I need 7:10 PM.What is the problem in my code?
public static String convertToLocalTimeFormat(String utcDateTimeString) {
SimpleDateFormat simpleDateFormat;
String formattedDateString = "";
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsedDateObject;
try {
parsedDateObject = simpleDateFormat.parse(utcDateTimeString);
SimpleDateFormat expectedSimpleDateFormat = new SimpleDateFormat("hh:mm a", Locale.getDefault());
formattedDateString = expectedSimpleDateFormat.format(parsedDateObject);
} catch (ParseException e) {
e.printStackTrace();
return formattedDateString;
}
return formattedDateString;
}
I would advise trying
System.out.println(expectedSimpleDateFormat.getTimeZone());
To see if all daylight saving schemes are correct on that device.

Android convert UTC Date to local timezone [duplicate]

This question already has answers here:
java date parse exception while conveting UTC to local time zone
(5 answers)
Closed 7 years ago.
I get this date string from my API : "2015-12-07T14:11:15.596Z"
But this date is in UTC format and I want to convert it in local time, how can I do it ?
I tried this :
try
{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return simpleDateFormat.parse(this.created_at);
}
catch (ParseException e)
{
Log.e("Error Date at Whisp", e.getMessage());
return null;
}
But it return me this error :
Unparseable date: "2015-12-07T13:21:17.996Z" (at offset 10)
your Date Format pattern is wrong. Change to:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
For more informations see the javadoc of SimpleDateFormat
The T and the Z are not in your mask
Either
created_at = created_at.replace ("T", "").replace ("Z", "");
or modifiy your mask

java ParseException: Unparseable date [duplicate]

This question already has answers here:
Java Unparsable date
(4 answers)
Closed 8 years ago.
I'm trying to convert a timestamp coming from a JSON API to a relative time span string like this:
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = sdf.parse(item.getTimeStamp());
long milliseconds = date.getTime();
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
milliseconds,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
The timestamp comes back in JSON like this: 2014-07-01T00:05:20Z
I'm throwing the exception for Unparseable date
What am I doing wrong here?
Z expects timezone value, change your pattern to and you don't need SSS since you don't have milliseconds in input
yyyy-MM-dd'T'HH:mm:ss'Z'

Categories