ISO 8601 datetime now - java

I need exactly that format in java which in C# is
DateTime.Now.ToString("o"). Sample returned date for DateTime.Now.ToString("o") is
2016-03-10T11:24:59.7862749+04:00
and then in sql it's inserted as
2016-03-10 11:24:59.786
I'm trying to insert same date format from java. I use that:
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
df.setTimeZone(tz);
String nowAsISO = df.format(new Date());
and it returns this
2016-03-10T07:29+0000
Because of that format then it goes in error. How can I change format to be exactly which I want?

For Java 7 you can use:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
System.out.println(df.format(new Date()));
This uses the pattern symbol XXX which will print the colon inside the offset, too. However, for Java-6 this feature is not offered. And the precision is always constrained to milliseconds.
For Java-8, you can also use:
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
System.out.println(OffsetDateTime.now().format(dtf)); // 2016-03-10T08:46:44.849+01:00
This enables nanosecond precision if such a clock is available (starting with Java-9).
For Java-6 either apply a hack based on SimpleDateFormat or use external libraries:
// Java-6 (SimpleDateFormat)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String text = sdf.format(new Date());
text = text.substring(0, text.length() - 2) + ":" + text.substring(text.length() - 2);
System.out.println(text);
// Joda-Time
DateTime now = DateTime.now();
System.out.println(DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ").print(now));
// Time4J
Moment now = SystemClock.currentMoment();
System.out.println(Iso8601Format.EXTENDED_DATE_TIME_OFFSET.withStdTimezone().format(now));

The Answer by Meno Hochschild is correct. I'll just add some more comments and some SQL-specific code.
Avoid Old Date-Time Classes
The old date-time classes, java.util.Date/.Calendar & java.text.SimpleDateFormat, are poorly designed, confusing, and troublesome. Avoid them.
The old clases have been supplanted by the java.time framework built into Java 8 and later.
For use before Java 8, check out the ThreeTen-Backport project.
Nanoseconds
The java.time classes have nanosecond resolution. So you will not have the problem of data loss where 2016-03-10T11:24:59.7862749+04:00 gets truncated to 2016-03-10 11:24:59.786 because of millisecond resolution used by the old classes.
Getting the current moment in Java 8 is limited to milliseconds, three digits of decimal fraction of second, due to legacy issue. Java 9 will get the current moment in nanoseconds, up to nine digits of decimal fraction (provided your computer’s hardware clock can provide such fine resolution).
ISO 8601
The ISO 8601 standard defines sensible text formats for date-time values. For example, 2016-03-09T23:24:33Z or 2016-03-09T22:24:33-01:00. The java.time classes use these by default, so no need to define parsing patterns.
Instant
An Instant is a moment on the timeline in UTC.
Instant instant = Instant.now();
Call Instant::toString to generate a string in standard format.
String output = instant.toString();
2016-03-09T23:24:33.123Z
OffsetDateTime
Apply a ZoneOffset to get an OffsetDateTime.
ZoneOffset zoneOffset = ZoneOffset.ofHoursMinutes( -5 , 30 );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );
ZonedDateTime
If you know the full time zone rather than just the offset-from-UTC, apply a ZoneId to get a ZonedDateTime.
Use proper time zone names.
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" ); // "Europe/Paris", "America/Montreal", etc.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
java.sql.Timestamp
Hopefully the JDBC drivers will be updated to directly use the java.time types. Until then we convert to java.sql types for transferring data in/out of database.
As noted above, java.time can handle nanoseconds. So does java.sql.Timestamp. But your database may not. Some databases are limited to whole seconds, milliseconds, or microseconds. When data is passed via JDBC to the database, the database may truncate.
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );
…and going the other direction…
Instant instant = ts.toInstant();
Note that an Instant is always in UTC by definition. So no need to perform the kind of code attempted at the end of the Question.
Work Flow
You should minimize your use of strings when working with date-time. Maximize your use of helpful date-time classes/objects, namely java.time classes. Stop thinking of strings as date-time values -- they are a textual representation of a date-time value.
Do not insert/retrieve date-time values to/from your database as strings. Use the java.sql objects such as java.sql.Timestamp and java.sql.Date. Use PreparedStatement and the "set/get" methods such as setTimestamp/getTimestamp. And virtually always define your columns in database as TIMESTAMP WITH TIME ZONE rather than “without time zone”.
When getting data from database, use the java.sql types. But as soon as is possible, convert to java.time types. The java.sql types are a mess, a dirty hack, and should be used only for data transfer not business logic.
Generally best to use UTC in your business logic, data storage, data exchange, API calls, and so on. Adjust into a time zone only when expected by a user or required by a data sink.

use this format "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Example:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
System.out.println(df.format(new Date()));

Related

Is there a format string for SimpleDateFormat to get milliseconds date-time value instead of human-readable form?

By means of classes like SimpleDateFormat it is possible to format time and date in a suitable format.
Examples here
https://developer.android.com/reference/java/text/SimpleDateFormat#examples
In Java it starts with milliseconds value and then that value gets translated into human readable format.
Sometime it is useful to have that value instead of the human readable form.
Example:
If I am not wrong the 1578738100000 value just means the UTC value Sat Jan 11 2020 10:21:40.
Is it possible to have a format string that yields a string with milliseconds instead of the human readable form?
I know that it is possible to get the milliseconds value directly from the Date class but what I am asking here is whether milliseconds are one of the possible format string to feed SimpleDateFormat (or similar classes) with.
Be clear in understanding that date-time value objects and formatter objects play different roles.
A date-time object has no format, it represents a date and/or time-of-day with or without the context of a time zone or offset-from-UTC.
A formatter has no value, no date nor time-of-day. A formatter’s job is to work with a date-time object to produce text in a certain format representing that date-time object’s value.
So tracking a count of milliseconds since the epoch reference is the job of the date-time object, not the formatter. Producing human-readable text is the job of the formatter. So, no, the formatter does not produce a count of milliseconds.
And, no, you should not be using a count of milliseconds to communicate date-time values. Such numbers have no meaning to a human reader which leads to easily missing erroneous data. And such data does not readily identify itself - is it a number of whole seconds, milliseconds, microseconds, or nanoseconds? And what is the epoch reference date, which of the couple dozen commonly used epochs?
Instead communicate date-time values as text using the ISO 8601 standard formats.
Another problem: you are using terrible date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
If your number is a count of milliseconds since the epoch reference of first moment of 1970 in UTC, parse as a Instant.
Instant instant = Instant.ofEpochMilli( 1_578_738_100_000L ) ;
If you insist on working with a count-from-epoch against my advice, you can interrogate the Instant.
long milliseconds = instant.toEpochMilli() ;
Generate text in standard ISO 8601 format.
String output = instant.toString() ;
For other formats, adjust the Instant into an OffsetDateTime or ZonedDateTime object, and generate text with a DateTimeFormatter. All this has been covered many many times already. So search Stack Overflow to learn more.
instant
.atZone(
ZoneId.of( "America/Montreal" )
)
.format(
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
)
Lastly, be aware that while the legacy classes were limited to a resolution of milliseconds, the java.time classes revolve to the much finer nanoseconds. So beware of possible data loss when calling Instant::toEpochMilli as any microseconds or nanoseconds are ignored,
The old and outdated SimpleDateFormat class cannot do that. Its replacement, the modern DateTimeFormatter, can.
DateTimeFormatter epochMilliFormatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.toFormatter();
Instant sampleInstant = OffsetDateTime
.of(2020, 1, 11, 10, 21, 40, 0, ZoneOffset.UTC)
.toInstant();
String formattedValue = epochMilliFormatter.format(sampleInstant);
System.out.println(formattedValue);
Output from this snippet is the number you mentioned:
1578738100000
Using ChronoField.INSTANT_SECONDS in the formatter gives us the seconds since the epoch. We wanted milliseconds, so we need to append ChronoField.MILLI_OF_SECOND immediately and make sure that they are printed in exact 3 positions, zero padded. This is what the 3 as 2nd argument to appendValue() does.
Is it possible to have a format string that yields a string with
milliseconds …?
No, with a format pattern string it is not possible, neither with SimpleDateFormat nor with DateTimeFormatter. You can go through the possible pattern letter of each and see that there is no pattern letter for neither seconds nor milliseconds since the epoch.
Are you sure that you want it, though? Even if this is for storing or for data interchange between systems, using milliseoncds since the epoch is not generally recommended exactly because they not human readable and therefore troublesome in debugging and in ad hoc queries. For most purposes you will be better off using a string in ISO 8601 format, like 2020-01-11T10:21:40Z. See the other answer by Basil Bourque for details. ISO 8601 format has been designed to be readable by both humans and computers.
You should not have wanted to use SimpleDateFormat anyway
The SimpleDateFormat class is notoriously troublesome (though even more for parsing than for formatting). It is also long outdated. The Date class that you mentioned is poorly designed and long outdated too. I recommend that you use java.time, the modern Java date and time API, as I do above.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Documentation of DateTimeFormatter with the format pattern letters that it accepts.
Wikipedia article: ISO 8601

Java: parse ISO_DATE / ISO_OFFSET_DATE

For a REST web service, I need to return dates (no time) with a time zone.
Apparently there is no such thing as a ZonedDate in Java (only LocalDate and ZonedDateTime), so I'm using ZonedDateTime as a fallback.
When converting those dates to JSON, I use DateTimeFormatter.ISO_OFFSET_DATE to format the date, which works really well:
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE;
ZonedDateTime dateTime = ZonedDateTime.now();
String formatted = dateTime.format(formatter);
2018-04-19+02:00
However, attempting to parse back such a date with...
ZonedDateTime parsed = ZonedDateTime.parse(formatted, formatter);
... results in an Exception:
java.time.format.DateTimeParseException: Text '2018-04-19+02:00' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {OffsetSeconds=7200},ISO resolved to 2018-04-19 of type java.time.format.Parsed
I also tried ISO_DATE and ran into the same problem.
How can I parse such a zoned date back?
Or is there any other type (within the Java Time API) I'm supposed to use for zoned dates?
The problem is that ZonedDateTime needs all the date and time fields to be built (year, month, day, hour, minute, second, nanosecond), but the formatter ISO_OFFSET_DATE produces a string without the time part.
When parsing it back, there are no time-related fields (hours, minutes, seconds) and you get a DateTimeParseException.
One alternative to parse it is to use a DateTimeFormatterBuilder and define default values for the time fields. As you used atStartOfDay in your answer, I'm assuming you want midnight, so you can do the following:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// date and offset
.append(DateTimeFormatter.ISO_OFFSET_DATE)
// default values for hour and minute
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.toFormatter();
ZonedDateTime parsed = ZonedDateTime.parse("2018-04-19+02:00", fmt); // 2018-04-19T00:00+02:00
Your solution also works fine, but the only problem is that you're parsing the input twice (each call to formatter.parse will parse the input again). A better alternative is to use the parse method without a temporal query (parse only once), and then use the parsed object to get the information you need.
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE;
// parse input
TemporalAccessor parsed = formatter.parse("2018-04-19+02:00");
// get data from the parsed object
LocalDate date = LocalDate.from(parsed);
ZoneId zone = ZoneId.from(parsed);
ZonedDateTime restored = date.atStartOfDay(zone); // 2018-04-19T00:00+02:00
With this solution, the input is parsed only once.
tl;dr
Use a time zone (continent/region) rather than a mere offset-from-UTC (hours-minutes-seconds). For any particular zone, the offset is likely to change over time.
Combine the two to determine a moment.
LocalDate.parse(
"2018-04-19"
)
.atStartOfDay(
ZoneId.of( "Europe/Zurich" )
) // Returns a `ZonedDateTime` object.
2018-04-19T00:00+02:00[Europe/Zurich]
From your REST service, either:
Return the date and zone separately (either with a delimiter or as XML/JSON), or,
Return the start of day as that is likely the intended outcome of a date with a time zone.
Separate your text inputs
The solution in the Answer by Walser is effectively treating the string input as a pair of string inputs. First the date-only part is extracted and parsed. Second, the offset-from-UTC part is extracted and parsed. So, the input is parsed twice, each time ignoring the opposite half of the string.
I suggest you make this practice explicit. Track the date as one piece of text, track the offset (or, better, a time zone) as another piece of text. As the code in that other Answer demonstrates, there is no real meaning to a date with zone until you take the next step of determining an actual moment such as the start of day.
String inputDate = "2018-04-19" ;
LocalDate ld = LocalDate.parse( inputDate ) ;
String inputOffset = "+02:00" ;
ZoneOffset offset = ZoneOffset.of( inputOffset) ;
OffsetTime ot = OffsetTime.of( LocalTime.MIN , offset ) ;
OffsetDateTime odt = ld.atTime( ot ) ; // Use `OffsetDateTime` & `ZoneOffset` when given a offset-from-UTC. Use `ZonedDateTime` and `ZoneId` when given a time zone rather than a mere offset.
odt.toString(): 2018-04-19T00:00+02:00
As you can see, the code is simple, and your intent is obvious.
And no need to bother with any DateTimeFormatter object nor formatting patterns. Those inputs conform with ISO 8601 standard formats. The java.time classes use those standard formats by default when parsing/generating strings.
Offset versus Zone
As for applying the date and offset to get a moment, you are conflating a offset-from-UTC with a time zone. An offset is simply a number of hours, minutes, and seconds. No more, no less. In contrast, a time zone is a history of the past, present, and future changes in offset used by the people of a particular region.
In other words, the +02:00 happens to be used by many time zones on many dates. But in a particular zone, such as Europe/Zurich, other offsets may be used on other dates. For example, adopting the silliness of Daylight Saving Time (DST) means a zone will be spending half the year with one offset and the other half with a different offset.
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( "Europe/Zurich" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
zdt.toString(): 2018-04-19T00:00+02:00[Europe/Zurich]
So I suggest you track two strings of input:
Date-only (LocalDate): YYYY-MM-DD such as 2018-04-19
Proper time zone name (ZoneId): continent/region such as Europe/Zurich
Combine.
ZonedDateTime zdt =
LocalDate.parse( inputDate )
.atStartOfDay( ZoneId.of( inputZone ) )
;
Note: The ZonedDateTime::toString method generates a String in a format that wisely extends the standard ISO 8601 format by appending the name of the time zone in square brackets. This rectifies a huge oversight made by the otherwise well-designed standard. But you can only return such a string by your REST service if you know your clients can consume it.
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, 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.
I found the solution (using TemporalQueries):
parse the date and zone separately, and restore the zoned date using that information:
LocalDate date = formatter.parse(formatted, TemporalQueries.localDate());
ZoneId zone = formatter.parse(formatted, TemporalQueries.zone());
ZonedDateTime restored = date.atStartOfDay(zone);

Java SimpleDateFormat time wierdness

I am trying to parse a date string into a java.util.Date using java.text.SimpleDateFormat; however, the resulting formatted date is wrong.
Here is a test case showing the issue:
#Test
public void testSimpleDateFormat() throws Exception {
String dateString = "2016-03-03 11:50:39.5960000";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSS");
Date date = format.parse(dateString);
assertEquals(dateString, format.format(date));
}
This results in the following failure:
org.junit.ComparisonFailure:
Expected :2016-03-03 11:50:39.5960000
Actual :2016-03-03 13:29:59.0000000
The date is correct, but the hours, minutes, seconds, and milliseconds are all wrong. Why is java.text.SimpleDateFormat messing up the time on my date?
Your pattern says that 5960000 is a number of milliseconds. That represents 5960 seconds, so approximately 1 hour and 39 minutes, which explains the difference between the date you obtain and the initial one.
java.time
You are using old classes that have proven to be confusing, troublesome, and poorly designed. Avoid them. They have been supplanted by the java.time framework built into Java 8 and later.
The java.time classes use resolution of nanoseconds, for up to nine digits of a decimal fraction of second. More than enough for your six digits (microseconds).
Your input string is close to the standard ISO 8601 format. That format is used by default in java.time for parsing/generating string representations of date-time values. So, need to specify parsing pattern.
Morph your input string into standard format. Replace the SPACE in the middle with a T.
String input = "2016-03-03 11:50:39.5960000";
String inputStandardized = input.replace( " " , "T" );
Parse that string into a date-time object.
LocalDateTime ldt = LocalDateTime.parse( inputStandardized );
To get an actual moment on the timeline, assign an offset or time zone intended for this input.
If in UTC, create a OffsetDateTime.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );
If a specific time was intended, create a ZonedDateTime.
ZonedDateTime zdt = ldt.atZone( ZoneId.of( "America/Montreal" ) ) ;
Before Java 8
If you do not yet have Java 8 technology available, consider adding either the backport of java.time or Joda-Time (the inspiration for java.time). For Android, there is a specific wrapper of the backport, ThreeTenABP.

How to convert MST time zone to IST format and then want to persist that in database in java

I am new to Java. I have a web application that runs on a godaddy server in the USA.
The problem is when we use the application anywhere we need to update the date with the respective timestamp in database. While updating it is storing as MST format date instead of IST format (when I tried from India). Let me know how can I solve this.
Thanks in advance.
My code is as follows.
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
f.setTimeZone(TimeZone.getTimeZone("IST"));
String date = f.format(new Date());
Date aptDate = formatter.parse(date);
System.Out.Print("The IST time is : "+ date);
Here I am getting the string format date, I want to convert into a date object and then store in the database.
When I apply the conversion it is giving earlier date. Let me what is the wrong going.
Your Question is confusing. Here are some guidelines to re-orient your thinking.
You are using old date-time classes now outmoded by the java.time framework built into Java 8 and later. Avoid the old classes as they are poorly designed, confusing, and troublesome.
Stop using the 3-4 letter codes such as IST. Do you mean India Standard Time or Irish? These codes are neither standardized nor unique. Erase these codes from both your thinking and your code. Use proper time zone names in the format of continent/region.
Do most of your work, your business logic, data exchange, data storage, and database in UTC. Apply a time zone only when expected by your user or data sink.
Use date-time types when defining columns in your database. Do not store date-time values as strings.
Use the java.sql types to transfer date-time values in and out of the database. Convert immediately to java.time types. Eventually JDBC drivers will be updated to use java.time types directly. Until that day, use new methods added to the old java.sql classes for convenient conversions.
An Instant is a moment on the timeline in UTC.
Instant now = Instant.now();
Convert to java.sql.Timestamp to write to the database.
java.sql.Timestamp ts = java.sql.Timestamp.from( now );
To the other direction, for retrieval, convert from java.sql to java.time.
Instant instant = myJavaSqlTimestamp.toInstant();
Notice that for database work we do not care about time zone as the values are all in UTC on all sides: Java, JDBC, SQL, database.
To view the wall-clock time for some locality, apply a time zone (ZoneId) to generate a ZonedDateTime object.
ZoneId zoneIdEdmonton = zoneId.of( "America/Edmonton" );
ZonedDateTime zdtEdmonton = ZonedDateTime.ofInstant( instant , zoneIdEdmonton );
You can apply yet another time zone. Note that java.time uses immutable objects. An new object arises from an old object rather than changing (“mutating”) the original. In this example, the zdtEdmonton object begets the zdtKolkata object.
ZoneId zoneIdKolkata = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdtKolkata = zdtEdmonton.withZoneSameInstant( zoneIdKolkata );

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

I am using following code to get date in "dd/MM/yyyy HH:mm:ss.SS" format.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateAndTime{
public static void main(String[] args)throws Exception{
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
String strDate = sdf.format(cal.getTime());
System.out.println("Current date in String Format: "+strDate);
SimpleDateFormat sdf1 = new SimpleDateFormat();
sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
Date date = sdf1.parse(strDate);
System.out.println("Current date in Date Format: "+date);
}
}
and am getting following output
Current date in String Format: 05/01/2012 21:10:17.287
Current date in Date Format: Thu Jan 05 21:10:17 IST 2012
Kindly suggest what i should do to display the date in same string format(dd/MM/yyyy HH:mm:ss.SS) i.e i want following output:
Current date in String Format: 05/01/2012 21:10:17.287
Current date in Date Format: 05/01/2012 21:10:17.287
Kindly suggest
SimpleDateFormat
sdf=new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
String dateString=sdf.format(date);
It will give the output 28/09/2013 09:57:19 as you expected.
For complete program click here
You can't - because you're calling Date.toString() which will always include the system time zone if that's in the default date format for the default locale. The Date value itself has no concept of a format. If you want to format it in a particular way, use SimpleDateFormat.format()... using Date.toString() is almost always a bad idea.
The following code gives expected output. Is that what you want?
import java.util.Calendar;
import java.util.Date;
public class DateAndTime {
public static void main(String[] args) throws Exception {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
String strDate = sdf.format(cal.getTime());
System.out.println("Current date in String Format: " + strDate);
SimpleDateFormat sdf1 = new SimpleDateFormat();
sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
Date date = sdf1.parse(strDate);
String string = sdf1.format(date);
System.out.println("Current date in Date Format: " + string);
}
}
Use:
System.out.println("Current date in Date Format: " + sdf.format(date));
tl;dr
Use modern java.time classes.
Never use Date/Calendar/SimpleDateFormat classes.
Example:
ZonedDateTime // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone).
.now( // Capture the current moment.
ZoneId.of( "Africa/Tunis" ) // Always specify time zone using proper `Continent/Region` format. Never use 3-4 letter pseudo-zones such as EST, PDT, IST, etc.
)
.truncatedTo( // Lop off finer part of this value.
ChronoUnit.MILLIS // Specify level of truncation via `ChronoUnit` enum object.
) // Returns another separate `ZonedDateTime` object, per immutable objects pattern, rather than alter (“mutate”) the original.
.format( // Generate a `String` object with text representing the value of our `ZonedDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // This standard ISO 8601 format is close to your desired output.
) // Returns a `String`.
.replace( "T" , " " ) // Replace `T` in middle with a SPACE.
java.time
The modern approach uses java.time classes that years ago supplanted the terrible old date-time classes such as Calendar & SimpleDateFormat.
want current date and time
Capture the current moment in UTC using Instant.
Instant instant = Instant.now() ;
To view that same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.
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( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Or, as a shortcut, pass a ZoneId to the ZonedDateTime.now method.
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ) ) ;
The java.time classes use a resolution of nanoseconds. That means up to nine digits of a decimal fraction of a second. If you want only three, milliseconds, truncate. Pass your desired limit as a ChronoUnit enum object.
ZonedDateTime
.now(
ZoneId.of( "Pacific/Auckland" )
)
.truncatedTo(
ChronoUnit.MILLIS
)
in “dd/MM/yyyy HH:mm:ss.SS” format
I recommend always including the offset-from-UTC or time zone when generating a string, to avoid ambiguity and misunderstanding.
But if you insist, you can specify a specific format when generating a string to represent your date-time value. A built-in pre-defined formatter nearly meets your desired format, but for a T where you want a SPACE.
String output =
zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
;
sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
Date date = sdf1.parse(strDate);
Never exchange date-time values using text intended for presentation to humans.
Instead, use the standard formats defined for this very purpose, found in ISO 8601.
The java.time use these ISO 8601 formats by default when parsing/generating strings.
Always include an indicator of the offset-from-UTC or time zone when exchanging a specific moment. So your desired format discussed above is to be avoided for data-exchange. Furthermore, generally best to exchange a moment as UTC. This means an Instant in java.time. You can exchange a Instant from a ZonedDateTime, effectively adjusting from a time zone to UTC for the same moment, same point on the timeline, but a different wall-clock time.
Instant instant = zdt.toInstant() ;
String exchangeThisString = instant.toString() ;
2018-01-23T01:23:45.123456789Z
This ISO 8601 format uses a Z on the end to represent UTC, pronounced “Zulu”.
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.
Here's a simple snippet working in Java 8 and using the "new" date and time API LocalDateTime:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss.SS");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
The output in your first printline is using your formatter. The output in your second (the date created from your parsed string) is output using Date#toString which formats according to its own rules. That is, you're not using a formatter.
The rules are as per what you're seeing and described here:
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString()
Disclaimer: this answer does not endorse the use of the Date class (in fact it’s long outdated and poorly designed, so I’d rather discourage it completely). I try to answer a regularly recurring question about date and time objects with a format. For this purpose I am using the Date class as example. Other classes are treated at the end.
You don’t want to
You don’t want a Date with a specific format. Good practice in all but the simplest throw-away programs is to keep your user interface apart from your model and your business logic. The value of the Date object belongs in your model, so keep your Date there and never let the user see it directly. When you adhere to this, it will never matter which format the Date has got. Whenever the user should see the date, format it into a String and show the string to the user. Similarly if you need a specific format for persistence or exchange with another system, format the Date into a string for that purpose. If the user needs to enter a date and/or time, either accept a string or use a date picker or time picker.
Special case: storing into an SQL database. It may appear that your database requires a specific format. Not so. Use yourPreparedStatement.setObject(yourParamIndex, yourDateOrTimeObject) where yourDateOrTimeObject is a LocalDate, Instant, LocalDateTime or an instance of an appropriate date-time class from java.time. And again don’t worry about the format of that object. Search for more details.
You cannot
A Date hasn’t got, as in cannot have a format. It’s a point in time, nothing more, nothing less. A container of a value. In your code sdf1.parse converts your string into a Date object, that is, into a point in time. It doesn’t keep the string nor the format that was in the string.
To finish the story, let’s look at the next line from your code too:
System.out.println("Current date in Date Format: "+date);
In order to perform the string concatenation required by the + sign Java needs to convert your Date into a String first. It does this by calling the toString method of your Date object. Date.toString always produces a string like Thu Jan 05 21:10:17 IST 2012. There is no way you could change that (except in a subclass of Date, but you don’t want that). Then the generated string is concatenated with the string literal to produce the string printed by System.out.println.
In short “format” applies only to the string representations of dates, not to the dates themselves.
Isn’t it strange that a Date hasn’t got a format?
I think what I’ve written is quite as we should expect. It’s similar to other types. Think of an int. The same int may be formatted into strings like 53,551, 53.551 (with a dot as thousands separator), 00053551, +53 551 or even 0x0000_D12F. All of this formatting produces strings, while the int just stays the same and doesn’t change its format. With a Date object it’s exactly the same: you can format it into many different strings, but the Date itself always stays the same.
Can I then have a LocalDate, a ZonedDateTime, a Calendar, a GregorianCalendar, an XMLGregorianCalendar, a java.sql.Date, Time or Timestamp in the format of my choice?
No, you cannot, and for the same reasons as above. None of the mentioned classes, in fact no date or time class I have ever met, can have a format. You can have your desired format only in a String outside your date-time object.
Links
Model–view–controller on Wikipedia
All about java.util.Date on Jon Skeet’s coding blog
Answers by Basil Bourque and Pitto explaining what to do instead (also using classes that are more modern and far more programmer friendly than Date)
If you are using JAVA8 API then this code will help.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTimeString = LocalDateTime.now().format(formatter);
System.out.println(dateTimeString);
It will print the date in the given format.
But if you again create a object of LocalDateTime it will print the 'T' in between the date and time.
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
System.out.println(dateTime.toString());
So as mentioned in earlier posts as well, the representation and usage is different.
Its better to use "yyyy-MM-dd'T'HH:mm:ss" pattern and convert the string/date object accordingly.
use
Date date = new Date();
String strDate = sdf.format(date);
intead Of
Calendar cal = Calendar.getInstance();
String strDate = sdf.format(cal.getTime());
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateAndTime{
public static void main(String[] args)throws Exception{
Date date = new Date(System.currentTimeMillis());
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS",
Locale.ENGLISH);
String strDate = format.format(date);
System.out.println("Current date in String Format: "+strDate);
}
}
use this code u will get current date in expected string format

Categories