Set random days on users with Date in Java? - java

I have for example 30 users and for everyone i want to set vacation with random start_day and random end_day of vacation. I want to use Date, not LocalDate. If i must do with LocalDate this is the answer.
LocalDate date = LocalDate.now();
List<VacationUser> collectVacationUser = allVacationUsers.stream()
.map(user -> {
if (inVacation()) {
return new VacationUser(date.minusDays(ThreadLocalRandom.current().nextInt(1, 5)),
date.plusDays(ThreadLocalRandom.current().nextInt(1, 5)));
} else {
return new VacationUser(user.getPrimaryEmail());
}
}).collect(toList());
return collectVacationUser;
}
I want to do this with Date, because in JSON date format with 'Date' is this "yyyy/mm/dd", in the other hand if I use LocalDate a format in JSON is something like this
"year":2018,"month":"AUGUST","era":"CE","dayOfMonth":16,"dayOfWeek":"THURSDAY","dayOfYear":228,"leapYear":false,"monthValue":8,"chronology":{"id":"ISO","calendarType":"iso8601"

tl;dr
Use types appropriate to your values: LocalDate
Never use the terrible legacy class java.util.Date
Learn to use converters/adapters in your Java⇔JSON serialization framework
Use standard ISO 8601 formats for date-time values whenever possible
Details
Use appropriate types to represent your data values. For a date-only value, without a time-of-day and without a time zone, the appropriate type is LocalDate.
Never use java.util.Date. That terrible class was supplanted years ago by the java.time classes.
As for generating textual representations in JSON, that is an entirely separate issue.
JSON has very few data types and none of them are date-time related. So whatever JSON output you are getting for your LocalDate input is a function of your particular Java-to-JSON library you are using. You do not divulge what library, so we cannot provide further assistance.
I can tell you that there is an established practical international standard for representing date-time values: ISO 8601. I strongly suggest always using these standard formats when serializing your date-time values to text.
For a date-only value, the standard format is YYYY-MM-DD such as 2018-01-23.
The java.time classes use these standard formats by default when parsing/generating strings.
LocalDate.parse( "2018-01-23" ) ;
And:
myLocalDate.toString()
2018-01-23
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

How to check a null sql date in java

I am developing a hospital management system for an assignment.I want to view patient details and display "not discharged" if the column date_of_discharge is null.I'm using mysql as database.Do I want to convert sql date to java util date before checking it null?
NULL is nothing
Do I want to convert … before checking it null?
No.
As others commented, NULL means “nothing at all”. A NULL is the same across all data types. So no need to convert, cast, or parse when simply asking if the value is NULL or not.
Instead of checking not null,can I directly check whether it is null
Yes. Use IS NULL or IS NOT NULL.
SELECT * FROM patient WHERE date_of_discharge IS NULL ;
…or…
SELECT * FROM patient WHERE date_of_discharge IS NOT NULL ;
Avoid NULLs
display "not discharged" if the column date_of_discharge is null.
Following Dr. Chris Date’s advice, I avoid using NULL wherever possible, as if it were the work of the devil (which it may be!).
Instead, assign a certain value of your own arbitrary choosing to signify no-value-yet-assigned. Perhaps the epoch reference date of Unix time and other systems: the first moment of 1970 in UTC, 1970-01-01T00:00Z.
In Java, we have available as pre-defined constants: LocalDate.EPOCH and Instant.EPOCH.
Never cast between java.util.Date & java.sql.Date
convert sql date to java util date before checking it null
No, never cast between these types. You should ignore the fact that java.sql.Date inherits from java.util.Date. By inheriting, the java.sql.Date actually carries a time-of-day. Yet java.sql.Date portrays itself as representing a date-only value without time-of-day and without time zone — but this is only a pretense. As a workaround, to fulfill that pretense, that time-of-day is set to midnight of some time zone. But the java.util.Date always represents a moment in UTC. So by casting, you will inadvertently be mixing in the effect of some time zone.
Confusing? Yes. This is a terribly bad design, an awful hack, and is one of many reasons to avoid these old legacy date-time classes. Use java.time classes instead.
JDBC 4.2
As of JDBC 4.2 we can directly exchange java.time objects with the database. Use PreparedStatement::setObject and ResultSet::getObject methods.
The java.sql.Date class that pretends to hold a date-only value is supplanted by the java.time.LocalDate. The LocalDate class actually does hold only a date, without a time-of-day and without a time zone.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
…and…
myPreparedStatement.setObject( … , localDate ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

GregorianCalendar Class in Java

I am trying to get current time in other time zone. I used this code for this:
GregorianCalendar calender = new
GregorianCalendar(TimeZone.getTimeZone("Asia/Bangkok"));
System.out.println(calender.getTime());
But, when I am running this code, this code provides the current time in CET as the time in my local machine is in CET.
I am confused. Then why there is scope to provide a TimeZone in constructor?
Ahh, the joys of the Java Date/Time API ...
What you want (aside from a better API, such as Joda Time) is a DateFormat. It can print dates in a time zone you specify. You don't need Calendar for that.
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
dateFormat.format(new Date());
Calendar is for time manipulations and calculations. For example "set the time to 10 AM". Then it needs the timezone.
When you are done with these calculations, then you can get the result by calling calendar.getTime() which returns a Date.
A Date is essentially a universal timestamp (in milliseconds since 1970, with no timezone information attached or relevant). If you call toString on a Date it will just print something in your default timezone. For more control, use DateFormat.
What you are doing right now is:
Getting a calendar in Bangkok time zone
get the Date object for this time( which is in ms since some date January 1, 1970, 00:00:00 GMT)
print out this Date in your timezone (Date.toString())
You should use a Formatter class to get the result you want. e.g. SimpleDateFormat
An alternative solution would be to use a less confusing Date/Time library. e.g. JodaTime or the new java.time package of Java8
tl;dr
ZonedDateTime.now( ZoneId.of( "Asia/Bangkok" ) )
java.time
The legacy date-time classes you are using are simply terrible, flawed in design and in implementation, built by people who did not understand date-time handling. Avoid those classes entirely.
Use only the modern java.time classes defined in JSR 310.
ZoneId z = ZoneId.of( "Asia/Bangkok" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Generate text in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.
String output = zdt.toString() ;
For other formats, use DateTimeFormatter as seen on hundreds of other Questions and Answers.
See this code run live at IdeOne.com.
2020-02-15T12:27:31.118127+07:00[Asia/Bangkok]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Storing timestamp with milliseconds in Oracle

I know how to retrieve timestamp with milliseconds:
to_char(systimestamp ,'YYYY-MM-DD HH24:MI:SS,FF9')
Can anyone please advise, is the timestamp data type sufficient to store the date with milliseconds or can I use varchar2? I am trying to insert this value from Java.
Yes, TIMESTAMP allows precision down to nanoseconds if you want it.
If you only need milliseconds, you just want a TIMESTAMP(3) column.
Use a java.sql.Timestamp (which again goes down to nanoseconds, if you need it to) on the Java side. Note that you should avoid doing your to_char conversion if possible - perform any string conversions you need client-side; fetch data as a timestamp, and send it as a timestamp.
tl;dr
Use smart objects, not dumb strings. Use java.time for nanosecond resolution.
myResultSet.getObject( … , LocalDateTime.class )
java.time
The Answer by Jon Skeet is correct, but now outdated. The java.sql.Timestamp class is supplanted by the java.time classes such as Instant and LocalDateTime.
The java.time classes have a resolution of nanoseconds, more than enough for your milliseconds.
Oracle database seems to have a TIMESTAMP type that is equivalent to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE. That means it lacks any concept of time zone or offset-from-UTC. For such a column, use LocalDateTime in Java as it too lacks any concept of zone/offset.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
For storing into a field of type similar to SQL-standard TIMESTAMP WITH TIME ZONE where do have respect for zone/offset, use Instant:
Instant instant = Instant.now() ; // Capture current moment as fine as nanoseconds. In practice, we get microseconds in Java 9, but only milliseconds in Java 8.
As of JDBC 4.2 and later, we can directly exchange java.time objects with the database via PreparedStatement.setObject and ResultSet.getObject. So use these smart objects rather than mere strings to communicate date-time values.
The java.time classes generate strings in standard ISO 8601 formats. Just call toString.
String output = instant.toString() ;
String output = ldt.toString() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Formatting Date in Thread safe Manner throws java.text.ParseException:

I am trying to convert the date from one format to Another
Input String - 2012-11-07-121603 (yyyy-MM-dd-HH-mm-ss)
Output String - 2012-11-07-12:16:03:000 (yyyy-MM-dd-HH:mm:ss:SSS)
ThreadSafeSimpleDateFormatUtil simpleDateFormat = new ThreadSafeSimpleDateFormatUtil(GenericConstants.DATE_FORMAT.YYYY_MM_DD_HH_MM_SS.toString());
final Date parsedDate = simpleDateFormat.parse(bulkCollectionTime);
simpleDateFormat = new ThreadSafeSimpleDateFormatUtil(GenericConstants.DATE_FORMAT.YYYY_MM_DD_HH_MM_SS_SSS.toString());
writeBean.setTimestamp(simpleDateFormat.format(parsedDate));
But it's throwing below error:
java.text.ParseException: Unparseable date: "2012-11-07-121603"
at java.text.DateFormat.parse(DateFormat.java:337)
at com.belgacom.rosy.rebecca.utils.ThreadSafeSimpleDateFormatUtil.parse(ThreadSafeSimpleDateFormatUtil.java:39)
Looks like the input format should be without the "-" between hours, minutes and seconds:
2012-11-07-121603 (yyyy-MM-dd-HHmmss)
Input String - 2012-11-07-121603 (yyyy-MM-dd-HH-mm-ss)
wrong pattern it would match with yyyy-MM-dd-HHmmss.
tl;dr
LocalDateTime.parse(
"2012-11-07-121603" ,
DateTimeFormatter.ofPattern( "uuu-MM-dd-HHmmss" )
).toString()
2012-11-07T12:16:03
java.time
The modern approach uses the java.time classes built into Java 8 and later. These classes are inherently thread-safe. These classes supplant the troublesome old legacy date-time classes that are un-thread-safe.
String input = "2012-11-07-121603" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuu-MM-dd-HHmmss" ) ;
Parse as a LocalDateTime because your input lacks info about time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input , f );
ldt.toString(): 2012-11-07T12:16:03
Thread-safety
The java.time classes are designed to be thread-safe. The classes use immutable objects. You may cache objects such as DateTimeFormatter for re-use throughout your code and across threads.
ISO 8601
When serializing date-time values to text, use standard ISO 8601 formats only. Do not invent your own formats such as that shown in your Question. The standard formats are practical and sensible. They are designed to be easy to parse by machine yet easy to read by humans across cultures.
The java.time classes use ISO 8601 formats by default when parsing/generating strings. Example shown above.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Parsing timestamp Soap fied to Java Date

I received from a SOAP message the follow date:
2012-11-16T02:02:05Z
How to parse to Date? What means this T and the Z in the date according with the SOAP specification?
I can parse correctly doing this way:
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(paymentDate);
Thanks #vikdor!
tl;dr
Instant.parse( "2012-11-16T02:02:05Z" )
ISO 8601
Your input string is in standard ISO 8601 format. That standard defines many useful, practical, unambiguous textual formats for representing date-time values.
The ISO 8601 formats are commonly adopted by modern protocols, such as XML schema, SOAP, etc., supplanting the clumsy outmoded formats such as RFC 1123 / RFC 822.
Your particular format from ISO 8601 uses:
T to separate the year-month-day portion from the hour-minute-second portion.
Z, short for Zulu, to indicate UTC time (an offset-from-UTC of +00:00).
Using java.time
Use the modern classes in the java.time package. They use ISO 8601 formats by default when parsing/generating strings.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.parse( "2012-11-16T02:02:05Z" ) ;
Capture the current moment in UTC.
Instant instant = Instant.now() ;
Generate a string in standard format by simply calling toString.
String output = instant.toString() ;
2017-07-26T01:23:45.704781401Z
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Categories

Resources