I need to be able to save and load the current time in java. I could use System.currentTimeMillis() to store it in a long, but I also need to be able to write it out in different formats, like; "yyyy-mm-dd", "dd/mm hour:min:sec", and such.
The program will save the time I got from System.currentTimeMillis() into a txt file, so even if something happens to the computer or program it needs to be able to just go right back to it's task.
tl;dr
Serializing
Serializing to text:
java.time.Instant.now().toString()
2018-01-01T01:23:45.123456789Z
Instantiate from text:
Instant.parse( “2018-01-01T01:23:45.123456789Z” )
Formatted strings
Adjust into time zone:
instant.atZone( ZoneId.of( “Africa/Tunis” ) ) // Instantiate a `ZonedDateTime` object
Generate strings in other formats:
DateTimeFormatter.ofPattern( … )
…or, better:
DateTimeFormatter.ofLocalized…
…then:
myZonedDateTime.format( formatter )
Track Date-Time Values, Not Milliseconds
Generally speaking, tracking date-time values by millisecond-since-epoch is tricky business and should be avoided. The values are meaningless when read by humans. Different software uses different numbers (seconds versus milliseconds versus nanoseconds). Different software uses different epochs (not always the beginning of 1970 as you may be expecting). Tracking by date-time values by milliseconds like trying to track text by bits rather than using String, FileReader, and FileWriter objects. We have good date-time libraries, so use them.
Joda-Time | java.time
By good date-time libraries, I am referring to Joda-Time or the new java.time package in Java 8. Avoid the older bundled classes, java.util.Date & .Calendar, as they are notoriously troublesome.
To get started with Joda-Time, try:
System.out.println( DateTime.now() );
Then search StackOverflow for "joda" or "joda date".
ISO 8601
When serializing date-time values to text storage, use the ISO 8601 format of YYYY-MM-DDTHH-MM-SS.sss+00:00 such as 2014-03-11T23:54:15+01:00 or 2014-03-11T22:54:15Z. This format is unambiguous. The format is intuitive across various cultures. The values when sorted alphabetically are also sorted chronologically.
The Joda-Time library uses the ISO 8601 format by default. Similarly the java.time package in Java 8 (inspired by Joda-Time, defined by JSR 310) also uses ISO 8601 but extends that format by appending in brackets the proper name of the time zone such as 2014-03-11T15:54:15+08:00[America/Los_Angeles].
store as long value returned from System.currentTimeMillis() and load back using Date date=new Date(long value);
You can use Calendar class or SimpleDateFormat as shown in below code:
import java.text.SimpleDateFormat;
import java.util.Calendar;
Calendar cal=Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
System.out.println(format.format(cal.getTime()));
Read more about Date formatting using SimpleDateFormat.
You can use code similar to the following
String formatted = new SimpleDateFormat("yyyy-mm-dd").format(new Date(System.currentTimeMillis()));
You'll need Date
http://docs.oracle.com/javase/7/docs/api/java/util/Date.html
And for formatting you need SimpleDateFormat
Date date = GregorianCalendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
System.out.println(sdf.format(date));
You can either use a text file or you could use the ObjectOutputStream because Date is Serializable.
Related
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
My understanding is:
2017-03-22T08:57:13-04:00 is the current time and offset w.r.t GMT
and yyyy-MM-dd HH:mm:ss.SSSS z is the GMT time.
I didnt find any java util to quickly convert this from one format to another. Do we need to use the string util to convert?
My preference would be to use the Java Date or Calendar Util to do the same.
Thanks,
G
I think with what you're asking you need to take a look at SimpleDateFormat
SimpleDateFormat might be of help here. Also DateTimeFormatter might be an option. The former accepts a pattern in the constructor and can then be used to convert a java.util.Date via new SimpleDateFormat(pattern).format(date).
DateTimeFormatter is part of the new Date API of Java8 and works similarly but with the new types like java.time.LocalDateTime, i.e. DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now()).
This has been covered many times already.
The old Date and Calendar classes are an awful mess, poorly designed, flawed, confusing, and troublesome. They are now legacy, supplanted by the modern java.time classes.
Your format is standard ISO 8601 format. These standard formats are used by default in the java.time classes.
OffsetDateTime.parse( "2017-03-22T08:57:13-04:00" )
.toInstant()
.toString()
.replace( "T" , " " )
2017-03-22 12:57:13Z
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()));
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
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