Creating timestamps and dates in java - java

There are many java classes that handle time (date, calander..etc) and there are even more references and tutorials online which makes it all very confusing and I don't know which class to use when.
Can anyone give me straightforward statements to do the following:
Create an instance of a timestamp to keep track of transactions on a database
Create an object that holds today's date in DD/MM/YY format (or anything similar)
Create an object that holds ANY given date in DD/MM/YY format (or anything similar)
Much appreciated!

Ans1
You can get current date using.
Date date = new Date();
In SQL you can mark the date field to update to current time automatically.
Ans2
SimpleDateFormat allows a variety of date formats. An example usage is:
Date d = new Date(secondsSunceEpoch);
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yy");
String time = df.format(d);
Ans3
Use parse method from SimpleDateFormat for any string would work.

try {
DateFormat todaysDateFormat = new SimpleDateFormat("dd/mm/yy");
Date date = new Date();
//2. datestring hold your today's object in DD/MM/YY format
String datestring = todaysDateFormat.format(date);
System.out.println("datestring "+datestring);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yy");
java.util.Date parsedDate;
parsedDate = dateFormat.parse(datestring);
Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
//1. Create an instance of a timestamp to keep track of transactions on a database
System.out.println(timestamp); // Use this time stamp as today's date foramt
// 3.Create an object that holds ANY given date in DD/MM/YY format
SimpleDateFormat dateFormat3 = new SimpleDateFormat("dd/mm/yy");
java.util.Date parsedDate3;
parsedDate3 = dateFormat.parse("30/12/14"); // any given date
String anyDatestring = todaysDateFormat.format(date);
// it will hold any date string
}catch (ParseException e) {
e.printStackTrace();
}

The other Answers are correct but outdated. They use troublesome old legacy classes. Instead use java.time classes.
1
Create an instance of a timestamp to keep track of transactions on a database
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
In Java 8 the current moment is captured with milliseconds resolution. In Java 9, up to nanosecond resolution. In both versions of Java, the Instant class is capable of holding a nanosecond value.
Instant now = Instant.now();
In JDBC 4.2 and later, exchange with your database via the PreparedStatement::setObject and ResultSet::getObject. If your driver cannot do so, convert to a java.sql.Timestamp.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
Going the other direction.
Instant instant = ts.toInstant();
2
Create an object that holds today's date in DD/MM/YY format (or anything similar)
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
To generate a String you can specify a formatting pattern, or just let DateTimeFormatter localize. A Locale determines (a) the human language used for translation, and (b) the cultural norms for deciding issues like capitalization, abbreviation, and punctuation.
DateTimeFormatter f = DateTimeFormatter.ofLocalizeDate( FormatStyle.SHORT ).withLocale( Locale.UK );
String output = today.format( f );
3
Create an object that holds ANY given date in DD/MM/YY format (or anything similar)
Do not conflate a date-time object with a String representation of that date-time value. The object can parse or generate such strings but is separate and distinct from the string.
So we already saw the solution above: a LocalDate object holds the date-only value. When needed for presentation to the user, generate a String to represent the value.
By the way, calling toString gets you a String in standard ISO 8601 format, YYYY-MM-DD.
String output = localDate.toString();
The java.time classes follow the immutable object pattern. So you do not modify an existing object to alter part of its value. Instead you create a new object with parts of its value based on the original object.
LocalDate tomorrow = today.plusDays( 1 );

Related

how to convert date in yyyy-MM-dd format of date type? [duplicate]

This question already has answers here:
Change date format in a Java string
(22 answers)
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
How to convert date in to yyyy-MM-dd Format?
(6 answers)
display Java.util.Date in a specific format
(11 answers)
Closed 3 years ago.
I know that this question that I am asking has answer all over the net but I want the yyyy-MM-dd format in Date type as SimpleDateFormat.format("yyyy-MM-dd") returns the string value and also I have tried SimpleDateFormat.parse("yyyy-MM-dd") but it does not provide the value in required format. Could anyone help how to get "yyyy-MM-dd" format in Date type variable. Example what I am trying to do is shown below-
Date date = new Date(); // this will give the outpur something like this Thu 28 Nov....
But I want the output in this format 2019-11-28 where date variable should not change its type.
tl;dr
Capture the current date, using java.time.LocalDate.
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.now( // Capture the current date. Time zone required, as the date is not the same around the globe.
ZoneId.of( "Pacific/Auckland" )
) // Returns a `LocalDate` object.
.toString() // Generates a `String` object whose text is in standard ISO 8601 format: YYYY-MM-DD
2020-01-23
Perhaps you are being handed a java.util.Date object by old code not yet updated to java.time classes. Convert from a given java.util.Date object (legacy) to Instant & ZonedDateTime (modern).
myJavaUtilDate // `java.util.Date` is one of the terrible date-time classes, now legacy.
.toInstant() // Convert to the modern `java.time.Instant` class that replaces `Date`.
.atZone( // Adjust from UTC to the time zone through which you want to perceive the date.
ZoneId.of( "Asia/Tokyo" ) // Specify a proper time zone in `Continent/Region` format, never 2-4 letter pseudo-zone such as PDT, CST, IST, and such.
) // Returns a `ZonedDateTime` object.
.format( // Generate text representing the value within our `ZonedDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE // Specify a formatter. Here, the standard ISO 8601 formatter for date-only value: YYYY-MM-DD.
) // Returns a `String`.
2020-01-23
java.time
You are using terrible date-time classes that were supplanted years ago by the java.time classes defined in JSR 310.
LocalDate
If you just want the current date, use LocalDate.now.
LocaleDate.now( ZoneId.of( "Europe/Berlin" ) ).toString() // Yields something like '2020-01-23'.
Instant
Convert java.util.Date to its replacement, java.time.Instant. Both represent a moment in UTC, though the modern class has a fiber resolution of nanoseconds versus milliseconds.
To convert, use new to/from methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
ZonedDateTime
For any given moment, the date varies around the globe by time zone. A few minutes after midnight in Paris France is a new day, while still “yesterday” in Montréal Québec.
So determining a date requires a time zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Text
Could anyone help how to get "yyyy-MM-dd" format in Date type variable.
Text has a “format”, but date-time objects do not. Date-time objects can be instantiated by parsing text. Date-time objects can generate text to represent t the value held internally. But the date-time object and the String object are separate and distinct.
Generate text for the date only, without the time of day and without the time zone appearing.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE ) ;
Convert it to java.sql.Date :
Date obj = new Date();
java.sql.Date sqlDate = new java.sql.Date(obj.getTime());
System.out.println(sqlDate);
Try this one:
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String strDate= formatter.format(date);
System.out.println(strDate);
or check this site: https://www.javatpoint.com/java-simpledateformat
I don't think that you can change the format of a Date object itself, therefore you should use DateFormatters, like mentioned above the SimpleDateFormat.
Also, you maybe should consider using LocalDate/LocalDateTime or Instant instead of Date.

Issue with String to Date conversion after Timezone parsing

I am trying to convert a date to a specified timezone and return the converted date. But the code always returns the unconverted date. Can any help with the same.
public static Date testUserSpecifiedConv(String toTimezone, Date inputDate) {
System.out.println(inputDate);
Date convertedDate = null;
String inputDateStr ;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone(toTimezone));
inputDateStr = df.format(inputDate);
System.out.println("Formatted Date In String Format: " + inputDateStr);
//Now trying to convert it back to date
try {
convertedDate = df.parse(inputDateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return convertedDate;
}
public static void main(String args[]) {
System.out.println("Formatted Date In Date Format: "+testUserSpecifiedConv("EST", new Date()));
}
Output is
Fri Mar 31 15:58:50 IST 2017
Formatted Date In String Format: 03/31/2017 05:28:50
Formatted Date In Date Format: Fri Mar 31 15:58:50 IST 2017
The formatted date in string and date format in output is different.
The class java.util.Date does represent a specific point in time and is timezone independent per se.
Nevertheless you can apply the timezone to the SimpleDateFormat to format your date accordingly to be presented in a certain timezone (e.g. if you want a formatted string to be shown somewhere).
Still, if you now parse back the formatted date, the date object itself will again not contain any information about the timezone.
If you want to work with timezones on an object level you might have a look into ZonedDateTime.
Update:
Assuming you want to convert a given String to an object containing the information about the date in a certain timezone you could do it like that:
ZonedDateTime dateTime = ZonedDateTime.parse("2007-12-03T10:15:30+01:00[Europe/Paris]");
Date instance does not retain any formatting information. For further details look at the Stackoverflow question. You will get your answer with a better insight to the Date object.
java.time
The Answer by JDC has the right idea.
I will show how to use the modern java.time classes that supplant the troublesome old legacy date-time classe (Date, Calendar, etc.) that should be avoided.
Firstly, your two arguments.
Pass ZoneId objects around rather than mere strings. Doing so provides type-safety, ensures valid values, and makes your code more self-documenting.
Date is outmoded, convert to Instant and pass that instead.
For time zone, specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
For the Date, convert to its equivalent in java.time, Instant. 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). Like Date, an Instant is always in UTC.
To convert between legacy classes and java.time classes, look to new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant();
Assign a ZoneId to generate a ZonedDateTime object.
ZonedDateTime zdt = instant.atZone( z );
Generate a string representing that value using a DateTimeFormatter. Do not conflate a date-time object with a string representation of its value.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss" , Locale.US );
String output = zdt.format( f );

Convert java.util.Date to different time zone requested

Depending on a request url, I have to convert a Date to different requested time zone and return date and time as String. I am using java 8 with spring boot and mongo 3.2
So inside the service method, I first set the time zone as below,
TimeZone.setDefault(TimeZone.getTimeZone(TIME_ZONE))
But I notice, it will change the time zone of whole java application. So even the method exit, the time zone would be remain the time zone I set previously.
So instead setDefault method level, I set it specifically in the SimpleDateFormat as below,
(assignment is a Assignmet document class having java.util.Date as a property named assignmentEndDate which map to a mongodb collection. In mongo db assignmentEndDate is store as UTC)
java.text.DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy'T'HH:mm:ss.SSS");
formatter.setTimeZone(TimeZone.getTimeZone(timezone));
Date assignmentEndDate = assignment.getAssignmentEndDate();
formatter.format(assignmentEndDate);
This way it wont change the application level time zone. Is this the correct approach for such scenario?
Take advantage of new date time api included in Java 8.
ZoneId zoneId = ZoneId.of("America/Chicago");
You can start with Instant, a java util date equalivent.
Instant instant = Instant.now();
ZonedDateTime zonedDateTime = instant.atZone(zoneId);
Or
You can also start with
using ZonedDateTime
You can take datetime as LocalDateTime, time zone agnostic class and convert to ZonedDateTime.
LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(zoneId);
You can easliy switch betweeen old date time classes & new time by accessing the helper methods on each of the new/old date time classes.
Change to java util date while saving to mongo database
//From ZonedDateTime to java util date.
Date oldDate = Date.from(zdt.toInstant());
//From Instant to java util date
Date oldDate = Date.from(instant);
//From Date to Instant.
Instant instant = date.toInstant();
All the new date time api have default formatter built into it.
//2007-12-03T10:15:30-06:00[America/Chicago]
String zonedDatetime = zonedDateTime.toString();
For specfic format you can always pass the DateTimeFormatter to the below method.
zonedDateTime.format(formatter)

How to display the time of a Date object based on DateFormat.SHORT and locale?

I am using Java 7 and I need to display the time part of a Java Date object.
I notice that DateFormat has the SHORT constant according to the page and the page has the following description:
SHORT is completely numeric, such as 12.13.52 or 3:30pm
My question is how to display only the time part (such as "3:30pm"). The following is what I have and it only shows the date part (such as 2/14/15):
DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT, A_Locale_object);
SimpleDateFormat sf = (SimpleDateFormat) f;
sf.format(new Date());
If what you want to display is the time part, what ou need to call is getTimeInstance(), and not getDateInstance().
This is the kind of answer that you should learn to find by yourself, simply by reading the javadoc:
Use getDateInstance to get the normal date format for that country. There are other static factory methods available. Use getTimeInstance to get the time format for that country. Use getDateTimeInstance to get a date and time format.
So If you want to display the time part, what you can do is provide the format to SimpleDatFormat and your locale like below
SimpleDateFormat sf = new SimpleDateFormat("hh:mm a", your_locale);
And format it like you did
sd.format(new Date()));
If you want more stuff to be formatted, you can definitely add more like "YY.MM.dd hh:mm a"
You can read the SimpleDateFormat document for more info http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Time Zone
The Question and other Answers neglect the crucial issue of time zone. If not specified, the JVM’s current default time zone is automatically applied.
Joda-Time
Such work is easier with the Joda-Time library.
Example using Joda-Time 2.7.
Translate the java.util.Date object to a Joda-Time DateTime object. Unlike a Date, a DateTime understands its assigned time zone. We want to adjust from the Date object’s UTC zone to a desired zone such as Montréal.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
DateTime dateTime = new DateTime( yourDate, zone ) ;
Generate a String representation of this date-time value. A pair of characters passed to forStyle control the full, long, short etc. format of the date portion and the time portion. A hyphen suppresses display of that portion.
DateTimeFormatter formatter = DateTimeFormat.forStyle( "-S" ).withLocale( Locale.CANADA_FRENCH ) ;
String output = formatter.print( dateTime ) ;
Use getTimeInstance instead of getDateInstance.
DateFormat f = DateFormat.getTimeInstance(DateFormat.SHORT,Locale.getDefault());

Formatting date in java

I am trying to format date string ex. 2014-11-24T18:30:00.000Z to 2014-11-24 using this code below:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.format(reqJsonObj.getString(FROM_DATE));
But it raises exception
java.lang.IllegalArgumentException: Cannot format given Object as a Date
Use dateFormat.parse() instead of dateFormat.format(), since you want to parse your String into Date object. Then, when you have the Date object, format it to String with wanted format. #Jens already gave you the full code, so no need to copy it again here.
You have to parse the string first as a date and then format the date:
SimpleDateFormat dateFormatP = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date parsedDate = dateFormatP.parse(reqJsonObj.getString(FROM_DATE));
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.format(parsedDate );
You need to give a date as the argument for format not a String. First create a SimpleDateFormat to parse the string to a date then give the date object to the other SimpleDateFormat to format the date.
USe this
Date date = formatter.parse(dateInString);
You specified one pattern, appropriate for the generating of a string you seek as your output. But you did define a pattern for parsing the input. You need to go from a string through parsing to a date-time object. Then use that object for generating a string.
Do not think of a string as a date-time but as a textual representation of a date-time value. Think of the date-time object as the actual value.
Avoid old date-time classes
You are using the old date-time classes that are poorly designed, confusing, and troublesome. Avoid classes such as java.util.Date/.Calendar.
java.time
Those old classes are supplanted by the java.time framework built into Java 8 and later.
An Instant is a moment on the timeline in UTC.
Instant now = Instant.now();
ISO 8601
The ISO 8601 standard defined sensible formats for textual representations of date-time values.
Both your input and output strings happen to comply with this standard.
The java.time classes use ISO 8601 as their default for parsing and generating strings. So no need for you to specify formatting patterns.
The Z on the end is short for Zulu which means UTC.
Instant instant = Instant.parse( "2014-11-24T18:30:00.000Z" );
What you want is a date-only value without time-of-day. The LocalDate class serves that purpose.
Determining a date requires an offset-from-UTC (or a full time zone). The Instant class is always in one particular offset, an offset of zero ( UTC), but is not really aware of that fact. Instant is only a basic building-block class.
The OffsetDateTime class is savvy about various offsets including UTC. We need to specify an explicit offset to make an OffsetDateTime. We will specify the handy constant for UTC, ZoneOffset.UTC.
OffsetDateTime odt = OffsetDateTime.of( instant , ZoneOffset.UTC );
The Instant and the OffsetDateTime are both a moment on the timeline in UTC. The difference is that OffsetDateTime is more flexible and has more features. We can ask the OffsetDateTime for our desired LocalDate object.
LocalDate localDate = odt.toLocalDate();
Now we simply call toString to generate output in standard ISO 8601 format.
String output = localDate.toString();
2014-11-24

Categories