Parse unknown DateTime string with Time Zone identifier [duplicate] - java

This question already has answers here:
Java DateTimeFormatter parsing with special characters
(2 answers)
Closed 1 year ago.
How can this string 20190612070000.000[-4:EDT] be parsed into ZonedDateTime?
I've tried this pattern and bunch of others, but nothing works so far:
String dateString = "20190612070000.000[-4:EDT]";
ZonedDateTime dateTime = ZonedDateTime.parse(dateString, ofPattern("yyyyMMddHHmmss.S[x:z]"));

There is no OOTB (Out-Of-The-Box) DateTimeFormatter with the pattern matching your date-time string. You can define one using DateTimeFormatterBuilder.
Demo:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("uuuuMMddHHmmss.SSS")
.appendLiteral('[')
.appendOffset("+H", "")
.appendLiteral(':')
.appendZoneText(TextStyle.SHORT)
.appendLiteral(']')
.toFormatter(Locale.ENGLISH);
String strDateTime = "20190612070000.000[-4:EDT]";
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
}
}
Output:
2019-06-12T07:00-04:00[America/New_York]
Learn more about java.time, the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Related

Convert date to BST java

I need to convert the date from 2021-08-21T17:36:51.000+00:00 to 2021-08-21 06:36 PM BST(+1) using java
any help
You can use OffsetDateTime#withOffsetSameInstant to meet this requirement.
Demo:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
OffsetDateTime source = OffsetDateTime.parse("2021-08-21T17:36:51.000+00:00");
OffsetDateTime target = source.withOffsetSameInstant(ZoneOffset.of("+01:00"));
System.out.println(target);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd hh:mm a O", Locale.ENGLISH);
String formatted = dtf.format(target);
System.out.println(formatted);
// Replace GMT with BST to get the required string
formatted = formatted.replaceFirst("GMT([+\\-]\\d+)", "BST($1)");
System.out.println(formatted);
}
}
Output:
2021-08-21T18:36:51+01:00
2021-08-21 06:36 PM GMT+1
2021-08-21 06:36 PM BST(+1)
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

How to parse a ISO 8601 to Date in Java?

I'm trying to parse a ISO 8601 date to a Date object, but I can't.
I'm trying the following:
String date = "2021-05-14T09:26:20";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
Date newDate = parser.parse(date);
System.out.println(format.format(newDate));
But I get this error:
Exception in thread "main" java.text.ParseException: Unparseable date: "2021-05-14T09:26:20"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.pruebas.pruebas.fechas.main(fechas.java:14)
How can I solve this?
Problems with your code:
The pattern for parsing should match with the given date-time string. You have missed 'T' in the pattern for parsing.
Also, you have used M instead of m for "Minute in hour". The symbol, M is used for "Month in year". Read the documentation carefully.
Demo with correct patterns:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
String date = "2021-05-14T09:26:20";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date newDate = parser.parse(date);
System.out.println(format.format(newDate));
}
}
ONLINE DEMO
Introducing java.time, the modern Date-Time API:
Note that the java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*, released in March 2014 as part of Java SE 8 standard library.
Solution using java.time, the modern Date-Time API:
The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String date = "2021-05-14T09:26:20";
LocalDateTime ldt = LocalDateTime.parse(date);
System.out.println(ldt);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
System.out.println(dtf.format(ldt));
}
}
Output:
2021-05-14T09:26:20
2023-02-14 09:02:20
ONLINE DEMO
Here, you can use y instead of u but I prefer u to y.
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Though #Arvind gave some good explanations and examples your issue in this particular instance is simply a typo. The string:
String date = "2021-05-14T09:26:20";
includes a T literal to separate the date from the time as per the ISO-8601 standard. You have simply forgotten this in your SimpleDateFormat:
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:MM:ss");
You should have this:
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
And all should work.

Convert LocalDate to TimeStamp with UTC

I am taking LocalDate as input and want to convert it into this format to search in oracle DB.
input - "2010-10-10"
Output- 10-OCT-10 07.39.02.713000000 AM UTC
I tried using TimeStamp and DateTime but getting date in these formats respectively.
2020-10-10 00:00:00.0
2020-10-10T00:00:00.000+05:30
I used
Timestamp.valueOf(startDate.atStartOfDay());
DateTime.parse(startDate.toString());
Can you please help me? Thank you in advance
Updated.
Parse the given string to LocalDate and convert it into ZonedDateTime using LocalDate#atStartOfDay(ZoneId).
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Testing {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2010-10-10");
ZonedDateTime zdt = date.atStartOfDay(ZoneId.of("Etc/UTC"));
System.out.println(zdt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS a zzz", Locale.ENGLISH);
System.out.println(dtf.format(zdt));
}
}
Output:
2010-10-10T00:00Z[Etc/UTC]
2010-10-10 00:00:00.000 AM UTC
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Don't pass date and timestamp to oracle as strings (varchar2), just use bind variables of required data types: oracle.sql.DATE or oracle.sql.TIMESTAMP.
You can convert(cast) them in Oracle. Also you can change timezones using SYS_EXTRACT_UTC, TO_UTC_TIMESTAMP_TZ or AT TIME ZONE

Converting epoch time stamp to readable date not working

I'm trying to use this code to convert the timestamp i have but the output is completely wrong, the output is 17/01/1970 16:56:28!!! it should be 8/7/2014 5:14:59 PM
Date date = new Date(1407388499);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
System.out.println(formatted);
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
formatted = format.format(date);
System.out.println(formatted);
Help me please
Your date is not long enough
new Date(1407388499);
Sat Jan 17 1970 15:56:28 GMT+0900 (Japan Standard Time)
new Date(1407388499000);
Thu Aug 07 2014 14:14:59 GMT+0900 (Japan Standard Time)
The value should be a Long that is the number of millseconds
Edit
So if your received number is
int dt = 1407388499:
Then you need to do
Date date = new Date(1000L * dt);
java.time
The root cause of the problem is that the Unix time specifies seconds since the Epoch whereas java.util.Date(long date) expects the number of milliseconds since the Epoch. So, you need to convert the Unix time into milliseconds and then pass the same to java.util.Date(long date).
However, the legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat etc.) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Solution using java.time, the modern API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochSecond(1407388499);
// Corresponding date-time in Australia/Sydney
ZonedDateTime zdtSydney = instant.atZone(ZoneId.of("Australia/Sydney"));
System.out.println(zdtSydney);
// Formatted
System.out.println(DateTimeFormatter.ofPattern("dd/MM/uuuu HH:mm:ss", Locale.ENGLISH).format(zdtSydney));
}
}
Output:
2014-08-07T15:14:59+10:00[Australia/Sydney]
07/08/2014 15:14:59
Learn more about java.time, the modern date-time API* from Trail: Date Time.
Solution using the legacy API:
Avoid performing calculations yourself if there is an OOTB (Out-Of-The-Box) API available for it e.g. TimeUnit#convert.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
Date date = new Date(TimeUnit.MILLISECONDS.convert(1407388499, TimeUnit.SECONDS));
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
System.out.println(format.format(date));
}
}
Output:
07/08/2014 15:14:59
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Time - hour minute manipulation

Is there an API to quickly manipulate (e.g. add, subtract) on time (hour, minute).
Pseudo code is listed below
Time t1 = "5 PM";
t1.add("5 minutes");
t1.subtract("90 minutes");
'course there is: http://download.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html#add%28int,%20int%29
You'll have to set the field parameter appropriately with one of the constants defined in the Field Summary section of the above page
java.time
The standard date-time library of Java SE 8 is rich with all such features.
Note: Quoted below is a notice at the Home Page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Given below is a demo of such features using java.time, the modern API:
import java.time.Duration;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalTime time = LocalTime.of(17, 30);
System.out.println(time);
time = time.plusMinutes(5);
System.out.println(time);
time = time.minusMinutes(90);
System.out.println(time);
// Parsing and formatting
DateTimeFormatter dtfInput = new DateTimeFormatterBuilder()
.appendPattern("h[:m[:s]] a") // Optional fields in square bracket
.parseCaseInsensitive() // Case-insensitive (AM/am/Am etc.)
.toFormatter(Locale.ENGLISH);
time = LocalTime.parse("5 PM", dtfInput);
System.out.println(time);
// Dealing with timezone?
ZonedDateTime zdt = ZonedDateTime.now().with(time);
System.out.println(zdt);
// Custom format
DateTimeFormatter timeAndZone12HourFormat = DateTimeFormatter.ofPattern("hh:mm:ss a'['VV']'");
DateTimeFormatter timeAndZone24HourFormat = DateTimeFormatter.ofPattern("HH:mm:ss'['VV']'");
System.out.println(zdt.format(timeAndZone12HourFormat));
System.out.println(zdt.format(timeAndZone24HourFormat));
// Adding/subtracting ISO 8601 Duration
Duration duration = Duration.parse("PT2H30M"); // 2 hours 30 minutes
zdt = zdt.plus(duration);
System.out.println(zdt.format(timeAndZone12HourFormat));
}
}
Output:
Learn more about java.time, the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Categories