Date with Time zone in Java [duplicate] - java

This question already has an answer here:
Converting the format of the date in java
(1 answer)
Closed 1 year ago.
My requirement is to have "YYYYMMDDHHMMSS.XXX [gmt offset[:tz name]]" date format (ex: 20140425053117.694[+5.30:IST]) for a Date field in Java.
I can achieve this simply using this SimpleDateFormat class which returns a String as output. But I want the output as a "Date" object with the above Pattern.
How can I achieve this, please help!!

The java.util.Date object encapsulates a long value that represents number of milliseconds since an epoch. In simple terms, you can think of Date class as a convenient way of storing a long number representing a date along with timezone information.
Whenever you want to display the date, you can format it any way, for example with SimpleDateFormat.
Prior to JDK 1.1, the java.util.Date could be used to parse and format dates. Starting from JDK 1.1 the parsing and formatting related methods of java.util.Date are deprecated.
Read more at Date class' javadoc page

I think it's what you want:
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");

Related

Translating from a String to a Timestamp and back [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I work with the date in my API on Java. I want to get today's date and time, write it to a class and then to a csv file (I use a csv file as a data store). Then, to implement the function of getting a report on records for today, to get it and to compare it with today's date (exactly the date, without time). What is the best way to do this? Right now I'm storing this in Timestamp, but it doesn't seem to be correct and should I use String? Then I need two parsers? To translate from a string to a date and time and from that to just a DATE? Which library is better to use for this?
I wrote a translation from a string to a timestamp, is this correct?
default Timestamp StringToTimestamp(String date) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
Date parsedDate = null;
try {
parsedDate = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
log.error("Error in date parsing");
}
return new Timestamp(parsedDate.getTime());
}
UPD
I changed my code for the java.time library, but it seems I did something wrong
default LocalDate StringToTimestamp(String date) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern('yyyy-mm-dd');
LocalDate date = LocalDate.parse(date, dtf);
return date;
}
UPD I edited the code according to the answer #OleV.V. It works really cool
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. I suggest writing the current date and time with offset from UTC to the CSV file.
OffsetDateTime dateTime = OffsetDateTime.now(ZoneId.systemDefault());
String stringForCsvFile = dateTime.toString();
System.out.println(stringForCsvFile);
Output when running in my time zone just now:
2020-12-26T11:02:07.368973+01:00
The string is in ISO 8601 format, which should be the best to avoid surprises for anyone reading it. The classes of java.time generally print ISO 8601 format from their toString methods.
Often you will value consistency higher than knowing which UTC offset was used when writing the file. If so, write the time in UTC to the file:
Instant now = Instant.now();
String stringForCsvFile = now.toString();
2020-12-26T10:02:07.373439Z
No matter which way you used above, after reading the timestamp from the file, convert like this:
ZoneId zone = ZoneId.systemDefault();
String stringFromCsvFile = "2020-12-26T11:02:07.368973+01:00";
ZonedDateTime dateTime = OffsetDateTime.parse(stringFromCsvFile)
.atZoneSameInstant(zone);
LocalDate dateFromCsv = dateTime.toLocalDate();
LocalDate today = LocalDate.now(zone);
System.out.println("Same day? " + dateFromCsv.isEqual(today));
Same day? true
I have made sure that both dates I compare are in the time zone of the JVM where the program is running. Please consider whether there’s a specific time zone you want, and if so, set zone to something like ZoneId.of("Asia/Baku"). It matters: it is never the same date in all time zones.
If you want to know whether the date is earlier or later, use the isBefore or isAfter method of LocalDate.
Was your code correct?
IMHO the worst problem with your code is using the old and poorly designed date-time classes: SimpleDateFormat, Date and Timestamp. SimpleDateFormat is a notorious troublemaker of a class. Date had severe design flaws in Java 1.0, therefore most constructors and methods were deprecated already in Java 1.1. Timestamp was never meant for other purposes than transferring high-precision timestamps to and from SQL databases (which we also don’t use it for anymore). And it’s a true hack on top of the already poorly designed Date class. I furthermore see nothing that you will want to use the high precision of Timestamp for, so using it here seems pointless.
There is a bug in your code: You are using upper case YYYY in your format pattern. This is for week year and only useful with a week number. I tried giving 24-06-2021 to your method. It returned 2021-01-04 00:00:00.0. It’s 5 months 20 days off because of the mentioned error. Apparently SimpleDateFormat defaulted to the start of week 1 in the week year and ignored the month and day of month.
As an aside, had you tried parsing with the same format pattern string with java.time, it would at least have told you that this was wrong.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Related question: java parsing string to date

Format a XMLGregorianCalendar with Italian date format(dd/mm/yyyy) with no time [duplicate]

This question already has answers here:
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
Closed 4 years ago.
I am trying to convert a java.util.Date to XMLGregorianCalendar in Italian format (dd/mm/yyyy) with no time. Whatever I try the output always prints yyyy-mm-dd.
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("Europe/Rome"));
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH),
DatatypeConstants.FIELD_UNDEFINED);
System.out.println(xmlDate);
I am a consumer of SOAP web-service, and the date attribute is defined as XMLGregorianCalendar.
Please advise how can I change the code to get the output with format (dd/mm/yyyy).
You don’t need an XMLGregorianCalender. It will not, cannot give you what you ask for. Instead you need a LocalDate and a DateTimeFormatter:
DateTimeFormatter italianDateFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.ITALIAN);
LocalDate date = LocalDate.now(ZoneId.of("Europe/Rome"));
String formattedDate = date.format(italianDateFormatter);
System.out.println(formattedDate);
When I ran this code today, the output was:
21/01/19
The difference from what you ask for is the two digit year, 19. If instead of FormatStyle.SHORT we use FormatStyle.MEDIUM, we get four digit year, but the month as a three letter abbreviaiton:
21-gen-2019
The advantage is that the code lends itself very well to internationalization: you just need to change the locale to get proper code for some other language and country. If you do need 21/01/2019 (with four digit year), specify the format explicitly using a pattern:
DateTimeFormatter italianDateFormatter
= DateTimeFormatter.ofPattern("dd/MM/uuuu");
21/01/2019
What’s wrong with using XMLGregorianCalendar?
When you call System.out.println(xmlDate), you are implicitly calling toString on your XMLGregorianCalendar. When it hasn’t got time and zone offset, toString always generates yyyy-MM-dd format, there is no way you can change that. On the other hand you can have any format you like in a String. Next obstacle is, there is no formatter that can format an XMLGregorianCalendar directly. You would need to convert to a different type, like ZonedDateTime, for example, first. Since you only want the date, neither the time of day nor the time zone, it’s simpler and easier to start out from LocalDate from the start. Not least for those reading and maintaining your code after you.
Your question mentions java.util.Date and your code uses GregorianCalendar too. Both of those classes are poorly designed and long outdated, fully replaced by java.time, the modern Java date and time API. So I suggest you don’t use them.
Link
Oracle tutorial: Date Time explaining how to use java.time, the modern Java date and time API.

How can I store a Date in yyyy-MM-dd HH:mm:ss format without having to change the Data type from Date in Java? [duplicate]

This question already has answers here:
Parse String to Date with Different Format in Java
(10 answers)
Closed 5 years ago.
Date x=someobject.getLastRanDate();
System.out.println(x);
For the above code, I am getting the output in yyyy-MM-dd HH:mm:ss format. How is this happening or how can we do this ?
Note : getLastRanDate() method is getting the date from Database which is storing in the Date Variable.
PS : Please don't answer about SimpleDateFormat.parse(). I explicitly mentioned output variable should be Date object.
In Java, a Date represents a point in time. It does not have any format. When you execute System.out.println, it calls toString() method of Date class which formats the dates into String using default format.
You can use SimpleDateFormat class to format the Date differntly. However, as far as storing the date in database is concerned, you don't need to worry about the format (it's just a representation really), you can define the column type as Date or Datetime (depending on requirement and database type) and use any framework to persist the Date object straight away.
Let's the documention explains itself with java.util.Date#toString()
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
Returns:a string representation of this date.
So this String is just a representation of the date.
From the same page, you are invited to see java.text.DateFormat that will explain how to change the format but also give you a subclass java.text.SimpleDateFormat explaining every pattern accessible to define your own format.
I can summarize the links more but the javadoc is quite resistant to time (I hope so)

Transform a String in unix time java android [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 6 years ago.
At the moment I have a String with the folowing format :
'DD/MM/YYYY' , and I'm willing to store this in a SQLite database as a date.
Since it is impossible to store it as a datetime, I've decided Integers would be the best choice, and someone told me about the Unix epoch solution. The thing is that I'm very unfamiliar with that, and I can't seem to convert a String into a unix epoch time...
Is there a way to directly convert a String with my format into a unix epoch time, or am I doing it wrong and should I change something?
I've read this question :Unix epoch time to Java Date object But still can not find my way out with my String...
Take a look at Parsing String date to date and adjust the format to yours.
If you have a java.util.Date just use http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getTime() to get the UNIX timestamp as long.
If in doubt, read the docs! ;)
https://developer.android.com/reference/java/text/SimpleDateFormat.html
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.parse(<value>);

How to convert time in YYYY-MM-DDTHH:mm:ss.SSSZ format to default timezone? [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 6 years ago.
The time that I am getting is in the format "2011-07-31T08:16:37.733Z". Actually the Z should be the timezone and then that time is converted to local timezone. How do I actually convert this time to default timezone now.
RFC 3339 describes a specific ISO 8601 'profile' for date/time representation.
If using 3rd-party open-source libraries is an option, take a look at Joda-Time's ISODateTimeFormat utility class.
Otherwise, if you need to roll out your own code it's not enough to use a SimpleDateFormat because of the way ISO 8601/RFC 3339 represents timezone information.
If all you need to parse is in 'Z' (Zulu or UTC), then it's relatively simple:
String input = "2011-08-11T01:23:45.678Z";
TimeZone utc = TimeZone.getTimeZone("UTC");
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
f.setTimeZone(utc);
GregorianCalendar cal = new GregorianCalendar(utc);
cal.setTime(f.parse(input));
System.out.println(cal.getTime());
Should print out "2011-08-11T01:23:45.678Z" in your local time zone.
If you need to handle arbitrary timezones in RFC 3339 then you'll need to extend the above to parse out the timezone designator and retrieve the corresponding Java TimeZone instance. That shouldn't be too hard if it's just whole hours +/- GMT, but in case of non-standard offsets you may have to create your own SimpleTimeZone instance.
private static SimpleDateFormat DATE_TIME_FORMAT=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
DATE_TIME_FORMAT.setTimeZone(TimeZone.getID()); //for example
date=DATE_TIME_FORMAT.format(curDate);

Categories