Print ZonedDateTime exactly as it is parsed - java-8

I have a date string in a format:
String date = 2014-05-05T05:05:00.000
ZonedDateTime zoneDateTime = LocalDateTime.parse(date).atZone(ZoneId.of("UTC");
the above prints:
2014-05-05T05:05Z[UTC]
Is there any way we can print it in the following format ?
2014-05-05T05:05:00.000Z
In joda time, i can easily do this:
DateTime datetime= org.joda.time.LocalDateTime.parse(date).toDateTime(UTC)

Is there any way we can print it in the following format ?
String date = 2014-05-05T05:05:00.000
You can use java.time.format.DateTimeFormatter.ofPattern().
String date = "2014-05-05T05:05:00.000";
ZonedDateTime zoneDateTime = LocalDateTime.parse(date).atZone(ZoneId.of("UTC"));
System.out.println(zoneDateTime);
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX").format(zoneDateTime));
Refrence: https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

Related

How to get TimeZone offset value in java

I have a date coming from a device and I want to do the following in Java:
I want to parse this date "2021-05-27T18:47:07+0530" to yyyy-mm-dd HH:MM:SS
Get the Date's offset value so that I can get the timezone offset as +05:30 or whatever timezone it comes from.
For the first one I have done this and looks like it works, but any better smaller approach will be handy as well:
String date = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ss+SSSS";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
LocalDateTime inputDate = null;
String outputDate = null;
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
inputDate = LocalDateTime.parse(date, inputFormatter);
outputDate = outputFormatter.format(inputDate);
System.out.println("inputDate: " + inputDate);
System.out.println("outputDate: " + outputDate);
The Ouput is:
inputDate: 2021-05-27T18:47:07.053
outputDate: 2021-05-27 18:47:07
I don't know how to get the offset value of timezone in this case.
There are many recommendations including using SimpleDateFormat and ZonedDateTime etc but should be the best answer for this considering the offset value can be dynamic i.e it can be +05:30,+09:00 etc.
Please help in this case.
Try it like this.
String dateTime = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ssZ";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(dateTime, dtf);
ZoneOffset tz = zdt.getOffset();
System.out.println(tz);
System.out.println(zdt.format(DateTimeFormatter.ofPattern(outputPattern,
Locale.ENGLISH)));
Prints
+05:30
2021-05-27 18:47:07
The zoned date time could also be reprinted using the same format by which it was originally parsed.

Swift DateFormatter Extract Time

I've been trying to return a date with just Time. I tried DateFormatter, but will always retrieve a full date for some reason.
//Declare Date Formatter 1
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss"
//Declare Date Formatter 2
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "hh:mm"
//Retrieve date and set to proper date for DateFormatter
var date: Date = dateFormatter1.date(from: "2017-11-28 10:47:30")!
//Set String date to time format with dateFormatter2
let dateString = dateFormatter2.string(from: item)
//Reseting dateFormatter1 for to only use time (could be ambiguous)
dateFormatter1.dateFormat = "hh:mm"
//Set date to Date
date = dateFormatter1.date(from: dateString)!
print("String: \(dateString)")
print("Date: \(date)")
Output:
String: 10:47
Date: 2000-01-01 15:47:00 +0000
- timeIntervalSinceReferenceDate : -31565580.0
I want the Date: to be 10:47
Is this even possible?
No, it is not possible. The Variable date is of type Date which has full date information within it. When showing it in string format you can convert it as you want, but while storing in the variable of type Date it stores the full information.

java.time.format.DateTimeParseException: Text could not be parsed at index 3

I am using Java 8 to parse the the date and find difference between two dates.
Here is my snippet:
String date1 ="01-JAN-2017";
String date2 = "02-FEB-2017";
DateTimeFormatter df = DateTimeFormatter .ofPattern("DD-MMM-YYYY", en);
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
When I run I get the error:
java.time.format.DateTimeParseException: Text could not be parsed at index 3
First of all, check the javadoc. The uppercase D represents the day-of-year field (not the day-of-month as you want), and uppercase Y represents the week-based-year field (not the year as you want). The correct patterns are the lowercase letters d and y.
Also, you're using month names in uppercase letters (JAN and FEB), so your formatter must be case insensitive (the default behaviour is to accept only values like Jan and Feb). And these month names are English abbreviations, so you must also use English locale to make sure it parses the names correctly (using java.util.Locale class).
So, your formatter should be created like this:
DateTimeFormatter df = new DateTimeFormatterBuilder()
// case insensitive to parse JAN and FEB
.parseCaseInsensitive()
// add pattern
.appendPattern("dd-MMM-yyyy")
// create formatter (use English Locale to parse month names)
.toFormatter(Locale.ENGLISH);
This will make your code work (and datediff will be 32).
The following code works. The problem is you are using "JAN" instead of "Jan".
DateTimeFormatter does not recognize that it seems. and also change the pattern to
"d-MMM-yyyy".
String date1 ="01-Jan-2017";
String date2 = "02-Feb-2017";
DateTimeFormatter df = DateTimeFormatter.ofPattern("d-MMM-yyyy");
LocalDate d1 = LocalDate.parse(date1, df);
LocalDate d2 = LocalDate.parse(date2, df);
Long datediff = ChronoUnit.DAYS.between(d1,d2);
Source: https://www.mkyong.com/java8/java-8-how-to-convert-string-to-localdate/
// DateTimeFormatterBuilder provides custom way to create a
// formatter
// It is Case Insensitive, Nov , nov and NOV will be treated same
DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
LocalDate datetime = LocalDate.parse("2019-DeC-22", f);
System.out.println(datetime); // 2019-12-22
} catch (DateTimeParseException e) {
// Exception handling message/mechanism/logging as per company standard
}
Maybe Someone is looking for this it will work with date Format like 3/24/2022 or 11/24/2022
DateTimeFormatter.ofPattern("M/dd/yyyy")
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/dd/yyyy");
formatter = formatter.withLocale( Locale.US ); // Locale specifies human language for translating, and cultural norms for lowercase/uppercase and abbreviations and such. Example: Locale.US or Locale.CANADA_FRENCH
LocalDate date = LocalDate.parse("3/24/2022", formatter);
System.out.println(date);
Maybe you can use this wildcard,
String d2arr[] = {
"2016-12-21",
"1/17/2016",
"1/3/2016",
"11/23/2016",
"OCT 20 2016",
"Oct 22 2016",
"Oct 23", // default year is 2016
"OCT 24", // default year is 2016
};
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder()
.parseCaseInsensitive().parseLenient()
.parseDefaulting(ChronoField.YEAR_OF_ERA, 2016L)
.appendPattern("[yyyy-MM-dd]")
.appendPattern("[M/dd/yyyy]")
.appendPattern("[M/d/yyyy]")
.appendPattern("[MM/dd/yyyy]")
.appendPattern("[MMM dd yyyy]");
DateTimeFormatter formatter2 = builder.toFormatter(Locale.ENGLISH);
https://coderanch.com/t/677142/java/DateTimeParseException-Text-parsed-unparsed-textenter link description here
Try using DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-LLL-yyyy",Locale.ENGLISH);

Assigning a DateTime to a Date database column

I have error:
Cannot implicitly convert type 'string' to 'System.DateTime'a
When I want get a DateTime
var dat = DateTime.Now.ToShortDateString();
godz.date = dat;
godz.data is type Date in database.
How fix it?
That's because you are trying to pass a string where a datetime is expected. Try changing to this:
var dat = DateTime.Now;
How about setting
godz.date = DateTime.Now;

Java Oracle date

String sql="select id from period where '"+systemDate+"' between startDate and endDate";
I need to execute this query and I am using oracle 10g. I want to get the id which falls between these dates. Problem I am facing is in oracle my date format is"dd-mon-yy" and systemDate is in format yyyy-mm-dd.So is ther any way to convert java date to dd-mon-format or any other way to execute the above query...
Kindly help.
You should convert your java.util.Date to a java.sql.Date and use a PreparedStatement as shown below:
java.util.Date jStartDate = ...; //your "java" date object
java.sql.Date startDate = new java.sql.Date(jStartDate.getTime());
java.util.Date jEndDate = ...;
java.sql.Date endDate = new java.sql.Date(jEndDate.getTime());
PreparedStatement p = connection.prepareStatement("select id from period where systemDate between ? and ?");
p.setDate(1, startDate);
p.setDate(2, endDate);
ResultSet rs = p.executeQuery();
Java has date formatting classes. DateFormat is the abstract parent class for these, SimpleDateFormat here is probably the one you want
SimpleDateFormat oracleStyle = new SimpleDateFormat("dd-MM-yy");
String dString = oracleStyle.format(systemDate);
String sql="select id from period where '"+systemDate+"' between startDate and endDate";
I havent tested this. The format call might need new string buffers as arguments, and my format string could be off, but this is the idea. Read the documentation

Resources