I have date objects formatted like
2011/06/13 17:52:20
and being returned as strings. How would I compare this against another date formatted the same way. I want to determine which one is greater than, less than or equal to, for a conditional statement I am forming.
Without reinventing the wheel (or making several cases) when there might already be a framework for doing this
Thanks!
use SimpleDateFormat to parse
use compareTo(..) of the Date objects that are obtained
For example:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);
int result = date1.compareTo(date2);
The result is (from the java.util.Date documentation):
the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.
It looks to me like your date format is yyyy/mm/dd hh:mm:ss. If that's the case, you can do a string compare and it will give you an accurate greater/less/equal. The string is coded as most signficant to least significant.
My colleagues pointed out to me last week that yyyy-MM-dd HH:mm:ss strings is completely compatible with the ordering of the underlying dates (as long as the fields are all zero padded). So you can just to the compareTo on the String values if they are more readily available.
Although SimpleDateFormat allows one to parse text into a date object, you're much better off storing the date as a Date object and parsing it on display.
Create/Store Date objects and use their built-in compareTo() method.
tl;dr
LocalDateTime.parse( "2011/06/13 17:52:20".replace( " " , "T" ) )
.isBefore( LocalDateTime.now() )
true
Details
The other Answers are correct in that you can either (a) alphabetically compare those particular strings, or (b) chronologically compare after parsing into date-time objects.
And be aware that date-time formats do not have a “format”. They contain date-time information. They can generate a String that is in a particular format, but the date-time object and the string are separate and distinct.
The other Answers use the troublesome old date-time classes that are now legacy, supplanted with the java.time classes.
Your inputs lack info about offset-from-UTC and time zone. So we must parse them as LocalDateTime objects. To parse, replace the SPACE in the middle with a T to comply with the ISO 8601 standard for formatting strings that represent date-time values.
String input = "2011/06/13 17:52:20".replace( " " , "T" );
LocalDateTime ldtThen = LocalDateTime.parse( input ) ;
LocalDateTime ldtNow = LocalDateTime.now( ZoneId.of( "America/Montreal" ) ) ;
Compare.
boolean ldtThenIsBefore = ldtThen.isBefore( ldtNow );
boolean ldtThenIsAfter = ldtThen.isAfter( ldtNow );
boolean ldtThenIsEqual = ldtThen.isEqual( ldtNow );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, 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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Related
I have to create the XMLGregorianCalendar object with this date format "YYYY-MM-DDTHH:MI:SS±TZ" e.g. "2015-07-01T17:42:49+04"
I have no idea how to do this. I've used a number of ways on how to convert date, but this pattern doesn't seem to work.
After some experiments I found that "YYYY-MM-dd'T'HH:mm:ssX" will give me the desired output. But it's a string and I can't achieve the same format with XMLGregorianCalendar.
It gives me "2015-07-01T17:42:4234+05:00", as you see there're additional symbols that i don't need.
Date-time objects have no format
XMLGregorianCalendar object with this date format
Date-time objects such as XMLGregorianCalendar do not have a “format”. They internally represent the date-time value in some manner, though not likely to be in text.
You can instantiate date-time objects by parsing text. And your date-time objects can generate text representing their internal value. But the text and the date-time object are distinct and separate from one another.
java.time
The XMLGregorianCalendar class is now obsolete. Supplanted by the modern java.time classes defined in JSR 310.
Parse your input string as a OffsetDateTime as in includes an offset-from-UTC but not a time zone.
OffsetDateTime odt = OffsetDateTime.parse( "2015-07-01T17:42:49+04" );
Generate text in standard ISO 8601 format.
String output = odt.toString() ; // Generates text in ISO 8601 format.
2015-07-01T17:42:49+04:00
Parts of an offset
The part at the end is the offset-from-UTC, a number of hours-minutes-seconds ahead or behind the prime meridian. In ISO 8601, the Plus sign is a positive number that means ahead of UTC. A Minus sign is a negative number that means behind UTC.
Suppressing parts of an offset
Some people may drop the seconds when zero, or drop the minutes when zero. But suppressing those digits does not change the meaning. These three strings all represent the very same moment:
2015-07-01T17:42:49+04
2015-07-01T17:42:49+04:00
2015-07-01T17:42:49+04:00:00
You said:
"2015-07-01T17:42:4234+05:00", as you see there're additional symbols that i don't need.
[I assume you really meant "2015-07-01T17:42:49+04:00" but made typos.]
You really should not care about this. Indeed, I recommend you always include both the hours and the minutes as I have seen multiple libraries/protocols that expect both hours and minutes, breaking if omitted. While the minutes and seconds are indeed optional in ISO 8601 when their value is zero, I suggest you always include the minutes when zero.
DateTimeFormatter
If you insist otherwise, you will need to use DateTimeFormatter class, and possibly DateTimeFormatterBuilder, to suppress the minutes when zero. Perhaps this:
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssx" );
String output = odt.format( f );
2015-07-01T17:42:49+04
The x code in that formatting pattern suppressed the minutes, and seconds, if their value is zero.
If doing your own formatting, be sure to not truncate when non-zero, or your result will be a falsehood (a different moment). Take for example, representing this moment as seen in India where current the offset in use is five and half hours (an offset that includes 30 minutes rather than zero).
ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = odt.atZoneSameInstant( z );
OffsetDateTime odtKolkata = zdt.toOffsetDateTime();
Dump to console.
System.out.println( "odtKolkata = " + odtKolkata );
2015-07-01T19:12:49+05:30
XMLGregorianCalendar
If you absolutely must use the old legacy class XMLGregorianCalendar, you can create one from the ISO 8601 output of our OffsetDateTime object seen in code above. See this Answer on another Question.
XMLGregorianCalendar xgc = null;
try
{
xgc = DatatypeFactory.newInstance().newXMLGregorianCalendar( odt.toString() );
}
catch ( DatatypeConfigurationException e )
{
e.printStackTrace();
}
System.out.println( "xgc.toString(): " + xgc );
xgc.toString(): 2015-07-01T17:42:49+04:00
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
String formatA ="yyyy-MM-dd'T'HH:mm:ss'Z'";
String formatB = "dd/MM/yyyy HH:mm:ss.SSS";
try {
XMLGregorianCalendar gregFmt = DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat(formatB).format(new Date()));
System.out.println(gregFmt);
} catch (DatatypeConfigurationException e) {
};
I am trying to formate XMLGregorianCalendar date .
The above code formats well for format "yyyy-MM-dd'T'HH:mm:ss'Z'"
But for formatB dd/MM/yyyy HH:mm:ss.SSS it throws error
java.lang.IllegalArgumentException
Do advice on how to fix it. Thank you so much!
log
Exception in thread "main" java.lang.IllegalArgumentException: 23/08/2017 16:13:04.140
at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl$Parser.parseAndSetYear(XMLGregorianCalendarImpl.java:2887)
at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl$Parser.parse(XMLGregorianCalendarImpl.java:2773)
at com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl.<init>(XMLGregorianCalendarImpl.java:435)
at com.sun.org.apache.xerces.internal.jaxp.datatype.DatatypeFactoryImpl.newXMLGregorianCalendar(DatatypeFactoryImpl.java:536)
at test.test.main(test.java:19)
line19 is line 4 , in the above code 'XMLGregorianCalendar gregFmt...'
The format that newXMLGregorianCalendar(string) accept is described in the XML specs and is different from the formatB you are trying to use.
tl;dr
Date-time objects do not have a “format”. They parse & generate String objects representing textually their value.
Use the modern java.time that replaced terrible old classes Date & XMLGregorianCalendar classes.
Example:
myXMLGregorianCalendar // If you must use this class… but try to avoid. Use *java.time* classes instead.
.toGregorianCalendar() // Converting from `javax.xml.datatype.XMLGregorianCalendar` to `java.util.GregorianCalendar`.
.toZonedDateTime() // Converting from `java.util.GregorianCalendar` to `java.time.ZonedDateTime`, from legacy class to modern class.
.format( // Generate a `String` representing the moment stored in our `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss.SSS" ) // Define a formatting pattern as you desire. Or better, automatically localize by calling `DateTimeFormatter.ofLocalized…` methods.
) // Returns a `String` object, distinct from our `ZonedDateTime` object.
07/07/2018 15:20:14.372
Date-time objects do not have a format
Do not conflate date-time objects with the strings they generate to represent their value. Date-time values, including the classes discussed below, are not a String, do not use text as their internal value, and do not have a “format”. All of them can generate, and parse, strings to represent their date-time value.
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes such as XMLGregorianCalendar.
The use of java.util.Date should be replaced with java.time.Instant. Both represent a moment in UTC. Instant uses a finer resolution of nanoseconds rather than milliseconds.
You can easily convert between the modern and legacy classes. Notice the new conversion methods added to the old classes, in this case java.util.GregorianCalendar::toZonedDateTime.
First convert from javax.xml.datatype.XMLGregorianCalendar to java.util.GregorianCalendar.
GregorianCalendar gc = myXMLGregorianCalendar.toGregorianCalendar() ;
Now get out of these legacy classes, and into java.time.
ZonedDateTime zdt = gc.toZonedDateTime() ;
All three types so far, the XMLGregorianCalendar, the GregorianCalendar, and the ZonedDateTime all represent the same moment, a date with time-of-day and an assigned time zone.
With a ZonedDateTime in hand, you can generate a String in standard ISO 8601 format extended to append the name of the time zone in square brackets.
String output = zdt.toString() ; // Generate string in standard ISO 8601 format extended by appending the name of time zone in square brackets.
2018-07-07T15:20:14.372-07:00[America/Los_Angeles]
You can generate strings in other formats using DateTimeFormatter class. For the formatting pattern listed second in your question, define a matching DateTimeFormatter object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss.SSS" ) ;
String output = zdt.format( f ) ;
07/07/2018 15:20:14.372
The first formatting pattern listed in your Question has a Z on the end, which means UTC and is pronounced “Zulu”. To adjust our ZonedDateTime to UTC, simply extract a Instant object. An Instant is always in UTC by definition.
Instant instant = zdt.toInstant() ; // Extract an `Instant` object, always in UTC.
Generate a String in the pattern shown first in the Question.
String output = instant.toString() ; // Generate string in standard ISO 8601 format.
2018-07-07T22:20:14.372Z
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.
this is the code which returns Date but at the client side i am getting
2016-12-26 14:18:57.0 at the client side . what is the possible solution .. I am using node.js at the client side. But I think it has nothing to do with this problem . I WANT TO REMOVE THIS 0
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
return date != null;
Try to set proper format in SimpleDateFormat constructor. Something like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String value = "2016-12-26 14:18:57";
Date date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
System.out.println("not equals");
}
System.out.println("date = " + date);
You are not giving a format pattern string to the SimpleDateFormat constructor, so it uses some default pattern. The solution is to provide a proper format string.
The formatting can be done like this:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss.SSS")
which would result e.g. in
29.02.2016 23:01:15.999
You want to omit the S format symbols (milliseconds) in the format string. E.g.:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss")
Of course you need to change this example to your format needs. Play a bit with the order and number of symbols, confer the docs.
tl;dr
LocalDateTime.parse(
"2016-12-26 14:18:57.0".replace( " " , "T" )
)
.truncatedTo( ChronoUnit.SECONDS )
.toString()
.replace( "T" , " " )
Avoid legacy date-time classes
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
ISO 8601
First replace the SPACE in the middle of your input string to make it comply with the standard ISO 8601 format.
String input = "2016-12-26 14:18:57.0".replace( " " , "T" );
LocalDateTime
Parse as a LocalDateTime given that your input string lacks any indication of offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input );
Generate a String by simply calling toString. By default an ISO 8601 format is used to create the String. If the value has no fractional second, no decimal mark nor any fractional seconds digits appear.
String output = ldt.toString ();
ldt.toString(): 2016-12-26T14:18:57
If you dislike the T in the middle, replace with a SPACE.
output = output.replace( "T" , " " );
2016-12-26 14:18:57
If your input might carry a fractional second and you want to delete that portion of data entirely rather than merely suppress its display, truncate the LocalDateTime object.
LocalDateTime ldtTruncated = ldt.truncatedTo( ChronoUnit.SECONDS ); // Truncate any fraction of a second.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I am trying to convert the date in milliseconds to the following ISO 8601 format:
But I am getting the following using SimpleDateFormat:
/**
* It converts the time from long to the ISO format
*
* #param timestampMillis
* #return isoDate
*/
public String convertTimeMillisToISO8601(String timestampMillis)
{
long timeInLong= Long.parseLong(timestampMillis);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
String isoDate = df.format(new java.util.Date(timeInLong));
return isoDate;
}
OUTPUT:
"ts":"2015-06-18T09:56:21+0000"
I know I can use substring to append the extra colon but Is there any better way to do so ?
For Java 7 and higher, you might use XXX (ISO 8601 time zone) in the date format String. According to the documentation, the result of X can be:
X => -08
XX => -0800
XXX => -08:00
but for all of those, it might as well return Z!
For Java 6 and earlier, there is no X (J6 doc), and since the result of X may or may not do what you want, I strongly recommend you just insert that colon yourself.
You can always use a StringBuilder:
new StringBuilder(
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.format(date))
.insert(22,':')
.toString();
For Java 8 if you use one of the standard ISO_DATE_* format patterns then the output formatted String will be truncated when the offset is +00:00 (UTC typically just appends Z).
OffsetDateTime utcWithFractionOfSecond = ZonedDateTime.parse("2018-01-10T12:00:00.000000+00:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME);
utcWithFractionOfSecond.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); // 2018-01-10T12:00:00Z ... not what you want!
The only solution I have found is using the outputPattern (shown below) that uses lowercase `xxx' to ensure that a colon is included in the timezone offset.
I have included an example with factions-of-a-second for completeness (you can remove the SSSSSS in your case)
DateTimeFormatter inputPattern = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
DateTimeFormatter outputPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSxxx");
OffsetDateTime utcWithFractionOfSecond = OffsetDateTime.parse("2018-01-10T12:00:00.000000+00:00", inputPattern);
OffsetDateTime utcNoFractionOfSecond = OffsetDateTime.parse("2018-01-10T12:00:00+00:00", inputPattern);
OffsetDateTime utcWithZ = OffsetDateTime.parse("2018-01-10T12:00:00Z", inputPattern);
OffsetDateTime utcPlus3Hours = OffsetDateTime.parse("2018-01-10T12:00:00.000000+03:00", inputPattern);|
utcWithFractionOfSecond.format(outputPattern ); // 2018-01-10T12:00:00.000000+00:00
utcNoFractionOfSecond.format(outputPattern); // 2018-01-10T12:00:00.000000+00:00
utcWithZ.format(outputPattern); // 2018-01-10T12:00:00.000000+00:00
utcPlus3Hours.format(outputPattern); // 2018-01-10T12:00:00.000000+03:00
In these examples I have used ISO_OFFSET_DATE_TIME only to create the input values for the test cases. In all cases it is the outputPattern yyyy-MM-dd'T'HH:mm:ss.SSSSSSxxx that controlling how to include a colon character in the timezone portion of your resulting formatted string.
Note that if your input data included the Zone ID like [Europe/London] then you would create your input data using ZonedDateTime instead of OffsetDateTime
Can you use Java 8?
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY-MM-dd'T'HH:mm:ssXXX");
System.out.println(formatter.format(ZonedDateTime.now()));
2015-04-15T17:24:19+09:00
tl;dr
OffsetDateTime.parse( "2014-06-18T09:56:21+00:00" )
2014-06-18T09:56:21Z
Details
Some other answers are close, correct in using the modern java.time classes that supplanted the terrible old legacy classes (Date, Calendar, SimpleDateFormat). But they are either working too hard or chose the wrong class.
ISO 8601
Your format is in standard ISO 8601 format. The java.time classes use these standard formats by default when parsing/generating text representing their date-time values. So you need not specify any formatting pattern at all. Works by default.
OffsetDateTime
Your input indicates an offset-from-UTC of zero hours and zero minutes. So we should use the OffsetDateTime class.
String input = "2014-06-18T09:56:21+00:00";
OffsetDateTime odt = OffsetDateTime.parse( input );
Zulu time
We can generate a string in standard ISO 8601 format by merely calling toString. The Z on the end means UTC, and is pronounced “Zulu”.
odt.toString(): 2014-06-18T09:56:21Z
ZonedDateTime
If your input indicated a time zone, rather than merely an offset, we would have used ZonedDateTime class. An offset is simply a number of hours, minutes, and seconds – nothing more. A time zone is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a particular region.
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.
I'm using struts2.x with jquery date picker.
I want to dispaly in the format dd/mm/yyyy. But from the database when fetching it is coming like yyyy-mm-dd.Then i converted it into the required format but the type is String. So next i Converted it to Date type. But the format is changed.
Date getRiskCommDate()
{
String fString = null;
System.out.println("Coming Date from DB"+riskCommDate);
if(riskCommDate!=null)
{
SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern("dd/MM/yyyy");
fString = format.format(riskCommDate);
}
System.out.println("Formated Date in String Form "+fString);
Date d = new Date(fString);
System.out.println("Formated Date in Date form Date "+d);
return d;
}
Output :
Coming Date from DB 2012-07-04
Formated Date in String Form 04/07/2012
Formated Date in Date form Date Sat Apr 07 00:00:00 IST 2012
Any idea is highly appreciated.
The java.util.Date class does not have any property to hold a format.
To display the value of the Date in a custom format, call the format method on SimpleDateFormat.
When you do this:
System.out.println(dateInstance)
…you are simply calling the toString() on the Date. That method returns the date in fixed format in String version.
Based on the comments
If you anyhow wants the custom format with date instance then you can either create a custom class wrapping date instance
class MyDate{
private Date date;
//provide appropriate accessor
//override toString() method to support required output
}
or extend Date
class MyDate extends Date{
//override toString() method to support required output
#Override
public String toString(){
//convert `this` to String with required format with the help of `SimpleDateFormat`
}
}
Date prints a format based on the Locale. It doesn't "remember" the format you gave it want you constructed it. Only Strings have a particular format, so if you need that, keep it as a String.
java.time
The old troublesome date-time libraries bundled with early Java have been supplanted by the java.time framework built into Java 8 and later. For Java 6 & 7, use the back-port, ThreeTen-Backport, and for Android the adaption thereof, ThreeTenABP. Avoid using the old java.util.Date/.Calendar and such.
LocalDate
The java.time classes include LocalDate for a date-only value without time-of-day and without time zone.
java.sql.Date
Hopefully JDBC drivers will be updated to deal directly with java.time types. Until then, use java.sql types for moving data in/out of database. The old java.sql classes have new to… and valueOf methods for conversion with java.time. Our interest here is in java.sql.Date.
LocalDate localDate = myJavaSqlDate.toLocalDate();
You can go the other direction, for submission to the database.
java.sql.Date myJavaSqlDate = java.sql.Date.valueOf( localDate );
Generate String
None of the discussed date classes (java.util.Date, java.sql.Date, java.time.LocalDate) have any “format”. Only textual representations of their values have a format. If you need a String, those classes can generate a String object for you. But do not confuse that String object with a date-time object as they are entirely separate and distinct.
The toString method on LocalDate use standard ISO 8601 format such as 2012-07-04 (meaning July 4, 2012).
String outputIso8601 = localDate.toString();
For other formats, use a DateTimeFormatter. Many other Questions and Answers on Stack Overflow have more discussion.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
String output = localDate.format( formatter ); // Generates a textual representation of the object’s date-only value.
Better yet, let java.time localize for you.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT );
formatter = formatter.withLocale( Locale.CANADA_FRENCH ); // or Locale.US, and so on.
String output = localDate.format( formatter );
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.