Related
This question already has answers here:
What is this date format? 2011-08-12T20:17:46.384Z
(11 answers)
Closed 24 days ago.
Any help or hint would be greatly appreciated. From the below code I get this date:2023-01-25 16:30:22.998. How can I get this date: "FrmDt": "2023-01-16T23:59:59.938Z". It has a "T" which I not sure what this mean?
java.util.Date tsFrom = new java.util.Date();
Calendar calFrom = Calendar.getInstance();
calFrom.setTime(tsFrom);
calFrom.add(Calendar.YEAR, -1);
tsFrom.setTime(calFrom.getTime().getTime()); // or
sqlTSFromDate = new Timestamp(calFrom.getTime().getTime());
System.out.println("From date:" + sqlTSFromDate);
tl;dr
OffsetDateTime
.now( ZoneOffset.UTC )
.minus( Period.ofYears( 1 ) )
.toString()
2022-01-27T02:02:36.985475Z
ISO 8601
Study the ISO 8601 standard formats for textually representing date-time values.
Avoid legacy classes
Never use the legacy classes Date, Calendar, Timestamp. They are terribly flawed, designed by people who did not understand date-time handling.
java.time
Instead, use the java.time classes defined in JSR 310.
Apparently you want one year prior to the the current moment as seen in UTC.
Capture the current moment in UTC.
OffsetDateTime oneYearAgoInUtc = OffsetDateTime.now( ZoneOffset.UTC );
now.toString(): 2023-01-27T02:02:36.985475Z
Go back a year, using calendar dates as seen in the offset of zero, in UTC. First define the amount of time to go back, using Period for a scale of years-months-days.
Period p = Period.ofYears( 1 );
Then subtract.
OffsetDateTime then = now.minus( p );
then.toString(): 2022-01-27T02:02:36.985475Z
See that code run at Ideone.com.
To generate text in standard ISO 8601, merely call toString. The java.time classes use ISO 8601 formats by default when generating/parsing text.
String output = then.toString() ; // By default, standard ISO 8601 format.
2022-01-27T02:02:36.985475Z
The T separates the year-month-day portion from the hour-minute-second portion.
The Z indicates an offset from UTC of zero hours-minutes-seconds.
As several comments said, this is an ISO 8601 date.
In java, you can parse or write using SimpleDateFormat.
With the Z at the end, makle sure to use UTC/Zulu time.
Amending your code:
public static String ISO_8601 = "yyyyMMdd'T'HHmmss'Z'";
...
SimpleDateFormat dateFormat = new SimpleDateFormat(ISO_8601);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
sqlTSFromDate = dateFormat.format(tsFrom)
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 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.
I am finding the current time using Date date3 = Calendar.getInstance().getTime();
This gives me Thu Oct 25 11:42:22 IST 2012
Now I want my Date to be in the format 2012.10.25 and that too as a Date object and not a string.
I tried using the below code
DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
Date startDate = df.parse(c_date1);
But when I finally use System.out.println(startDate.toString()); it again gives me
Thu Oct 25 00:00:00 IST 2012. that is practically because the toString() function has been implemented in a way to show this format.
So is there any other way to get the date as 2012.10.25 and that too as the Date format. Date object is required because it is to be saved in db as a date field.
you need to use df.format(Date) method to get date in required format
Date date3 = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
System.out.println(df.format(date3));
Date date3 = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd");
java.sql.Date date = null;
try {
date =new java.sql.Date(df.parse(df.format(date3)).getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(date);
tl;dr
Avoid terrible legacy date-time classes (Date, SimpleDateFormat). Use only the modern java.time classes.
LocalDate.now( // Instantiate a date-only object, without time-of-day and without time zone.
ZoneId.of( "India/Kolkata" ) // Capture the current date, “today”, as seen by the people in a certain region (a time zone). For any given moment, the date varies around the globe by zone.
)
.format( // Generate a String whose text represents the date-time value of our `LocalDate` object.
DateTimeFormatter.ofPattern( "uuuu.MM.dd" ) // Specify your desired formatting pattern.
)
2012.10.25
To insert the date-only value for the current date into your database:
myPreparedStatement.setObject(
… ,
LocalDate.now( ZoneId.of( "India/Kolkata" ) )
) ;
Confusing date-time value with a String
Date-time values do not have a “format”. Only strings have a format. Do not conflate the two. A date-time object can be instantiated by parsing a String. And a date-time object can generate a String to represent its value textually. But the date-time object and such strings remain separate and distinct.
it again gives me Thu Oct 25 00:00:00 IST 2012. that is practically because the toString() function has been implemented in a way to show this format.
No, the toString method does not “show” this format. That wording implies the format lives within the Date object. But the format does not live inside the Date object – the Date has no “format” at all. The toString method generates a String whose characters are arranged into this format.
Confusing date-only with date-time
You seem to interesting in a date-only values, without a time-of-day and without a time zone. If so, use the LocalDate class.
Create a LocalDate object for your desired value by parsing a string. Easiest to use the standard ISO 8601 format used by default in the java.time classes: YYYY-MM-DD.
String input = "2012-10-25" ;
LocalDate ld = LocalDate.parse( input ) ; // No need to specify a formatting pattern, as ISO 8601 format used by default.
Your input string is in a non-standard format. Happens to be the same year-month-day order, so I would just replace the FULL STOP dots with hyphens.
String input = "2012.10.25".replace( "." , "-" ) ; // Convert from custom format to standard ISO 8601 format.
LocalDate ld = LocalDate.parse( input ) ; // No need to specify a formatting pattern, as ISO 8601 format used by default.
Or specify a formatting pattern.
String input = "2012.10.25" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu.MM.dd" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
Use that same formatter object to generate a string.
String output = ld.format( f ) ; // Generate a string in this custom format.
Current date
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.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
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" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Database
As of JDBC 4.2 and later, we can directly exchange java.time objects with a database.
If storing this LocalDate object to a SQL-standard DATE column:
myPreparedStatment.setObject( … , ld ) ;
And retrieval:
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
If storing to a SQL-standard TIMESTAMP WITH TIME ZONE column, we need a date-time value rather than our date-only value. Perhaps you want to use the first moment of the day on that date? If so, let java.time determine that first moment. Do not assume 00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ; // First moment of the day for that date for the people in India.
Most databases store zoned date-time moments by adjusting into UTC. Your JDBC driver and database may do that for you, or you can extract a UTC value (Instant) from your ZonedDateTime.
Instant instant = zdt.toInstant() ; // Adjust from zoned time to UTC time.
myPreparedStatment.setObject( … , instant ) ;
And retrieval:
Instant instant = myResultSet.getObject( … , Instant.class ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
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.
Date object do not have any format. i.e. you can not convert any Date object into perticular format. Becuase it has its own to string format which will return when you print any date. You can convert any string format only.
You can convert or construct any Date Object from date string of the specific format. but that date object will not be in a specific format.
Your question is just like asking:
I have an int variable of value 1234567, and I want it to store as "1,234,567" in that variable.
It is simply not reasonable.
How a value is stored, is nothing to do with how the value is presented.
If you want to save a date in db in given date format the you can use
DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
Date date3 = Calendar.getInstance().getTime();
String startDate = df.format(date3);
try {
java.sql.Date date = new java.sql.Date(df.parse(startDate).getTime());
System.out.println(date);
} catch (ParseException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
It's very simple
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
format.parse(dateObject.toString());
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