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
Related
I am trying to make timestamps from a csv of timestamp strings,
eg "21-Mar-21 05:01:26 GMT" and "19-Jul-21 1:08:22 BST"
SimpleDateFormat("dd-MMM-yy hh:mm:ss")
gets the Date.
Is it possible to get the ZoneId from the "GMT" or "BST" strings? (BST being British Summer Time)
or do I need to hardcode a structure mapping one to the other?
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. Since java.sql.Timestamp extends java.util.Date, it inherits all undesirable things from its parent type. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
import java.time.OffsetDateTime;
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) {
String strDateTime = "21-Mar-21 05:01:26 GMT";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-uu HH:mm:ss VV", Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
// Getting ZoneId
ZoneId zoneId = zdt.getZone();
System.out.println(zoneId);
// If required, get OffsetDateTime from the ZonedDateTime
OffsetDateTime odt = zdt.toOffsetDateTime();
System.out.println(odt);
}
}
Output:
2021-03-21T05:01:26Z[GMT]
GMT
2021-03-21T05:01:26Z
ONLINE DEMO
Check this answer and this answer to learn how to use java.time API with JDBC.
If at all you need java.sql.Timestamp:
For any reason, if you need java.sql.Timestamp, simply get Instant out of the ZonedDateTime and derive the value of Timestamp using Timestamp#from.
Timestamp timestamp = Timestamp.from(zdt.toInstant());
System.out.println(timestamp);
If you just need java.sql.Timestamp, you can do it in the following alternative easier way:
import java.sql.Timestamp;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "21-Mar-21 05:01:26 GMT";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-uu HH:mm:ss VV", Locale.ENGLISH);
Instant instant = Instant.from(dtf.parse(strDateTime));
Timestamp timestamp = Timestamp.from(instant);
System.out.println(timestamp);
}
}
Output:
2021-03-21 05:01:26.0
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
Update:
This update is based on the following valuable comment by Ole V.V.:
new DateTimeFormatterBuilder().appendPattern("dd-MMM-uu H:mm:ss ").appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Europe/London"))).toFormatter(Locale.ENGLISH)
parses 19-Jul-21 1:08:22 BST into
2021-07-19T01:08:22+01:00[Europe/London], which agrees with what the
OP wanted. The mentioned datetime string has 1 digit hour of day, 1,
so we need just one H (which in turn also accepts the 05 from the
other string example).
Demo:
import java.sql.Timestamp;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.TextStyle;
import java.util.Locale;
import java.util.Set;
public class Main {
public static void main(String[] args) {
String strDateTime = "19-Jul-21 1:08:22 BST";
DateTimeFormatter dtf =
new DateTimeFormatterBuilder()
.appendPattern("dd-MMM-uu H:mm:ss ")
.appendZoneText(TextStyle.SHORT, Set.of(ZoneId.of("Europe/London")))
.toFormatter(Locale.ENGLISH);
Instant instant = Instant.from(dtf.parse(strDateTime));
Timestamp timestamp = Timestamp.from(instant);
System.out.println(timestamp);
}
}
Output:
2021-03-21 05:01:26.0
ONLINE DEMO
* 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.
If you know that GMT and BST are the only time zone abbreviations you will need, and you know for a fact that British Summer Time is the intended interpretation of BST, you can safely use the good answer by Arvind Kumar Avinash.
If there may be more time zone abbreviations in your input and you also know the correct interpretation for those, extending the answer is not difficult. Just pass a larger set of preferred time zones to DateTimeFormatterBuilder.appendZoneText(). For the sake of the example for the following formatter I have specified that BST is British Summer Time, PST is for Pitcairn Standard Time and CST means Cuba Standard Time.
Set<ZoneId> preferredZones = Set.of(ZoneId.of("Europe/London"),
ZoneId.of("Pacific/Pitcairn"), ZoneId.of("America/Havana"));
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("dd-MMM-uu H:mm:ss ")
.appendZoneText(TextStyle.SHORT, preferredZones)
.toFormatter(Locale.ENGLISH);
If you don’t know which time zone abbreviations may turn up in your data or you are not sure of the correct interpretation of each one of them, I think that’s it’s better to give up on the task. Sorry. Those abbreviations are very often ambiguous. Rather than a false result from interpreting the abbreviation wrongly your users will prefer a message stating that you cannot interpret the time zone abbreviation.
Link: Time Zone Abbreviations – Worldwide List.
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.
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.
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.
I'm trying to convert some string that is in UTC time to a java Calendar object that should be set to GMT-5.
My current UTC string input is this:
UTC date : 20050329174411
I use this code (I detect the 'pattern' as shown below):
DateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = dateFormat.parse(utcDate);
calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-5"));
calendar.setTime(date);
I then printed the time like this:
calendar.getTime()
And I got this result:
GMT date : Tue Mar 29 17:44:11 EST 2005
I need to support theses date/time string patterns:
FORMAT_UTC4 = "yyyy";
FORMAT_UTC6 = "yyyyMM";
FORMAT_UTC8 = "yyyyMMdd";
FORMAT_UTC10 = "yyyyMMddHH";
FORMAT_UTC12 = "yyyyMMddHHmm";
FORMAT_UTC14 = "yyyyMMddHHmmss";
I would be expecting the time to be set to "12:44:11". I have read a couple of examples and I find date time handling pretty confusing. For me, it's always the same, I get some sort of string formatted UTC and I convert it to GMT-5. I really feel it should be easy!
Ref 1 : How can I get the current date and time in UTC or GMT in Java?
Ref 2 : How to handle calendar TimeZones using Java?
You must set the SimpleDateFormat's time zone to UTC before parsing the date. Else, it uses your default timezone.
And to display the date in the "GMT-5" timezone, you should use another DateFormat, with the timezone set to GMT-5, and format the date with this DateFormat. The toString() method of Date uses your default time zone to transform the date into something readable.
java.time
Note that GMT-5 or timezone offset of -05:00 hours is a fixed offset i.e. independent of the DST and type to represent a date-time with timezone offset is OffsetDateTime.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochMilli(20050329174411L);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-05:00"));
// Alternatively
// OffsetDateTime.ofInstant(instant, ZoneOffset.of("-05:00"));
System.out.println(odt);
}
}
Output:
2605-05-15T18:52:54.411-05:00
If you are looking for an automatic adjustment of timezone offset as per the DST, use ZonedDateTime.
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochMilli(20050329174411L);
ZonedDateTime zdt = instant.atZone(ZoneId.of("America/Chicago"));
// Alternatively
// ZonedDateTime.ofInstant(instant, ZoneId.of("America/Chicago"));
System.out.println(zdt);
}
}
Output:
2605-05-15T18:52:54.411-05:00[America/Chicago]
Learn more about java.time, the modern date-time API* from Trail: Date Time.
If at all you need an object of java.util.Calendar from this object of ZonedDateTime, you can do so as follows:
Calendar calendar = Calendar.getInstance();
calendar.setTime(Date.from(zdt.toInstant()));
* 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.