XMLGregorianCalendar to GregorianCalendar - java

I was simply trying to convert the instance of XMLGregorianCalendar (which I got from JAXWS) to GregorianCalendar in specific TimeZone using below code.
The date is coming in EST and I want to convert it into GMT for further saving to DB
//soap response <ns4:TimeStamp>2016-06-18T04:43:54-04:00</ns4:TimeStamp>
//dtime is what i got from JAXB for the above date, so I wrote::
Date date = dTime.toGregorianCalendar(TimeZone.getTimeZone("UTC"), Locale.US, null).getTime();
System.out.println(date);
Output: Sat Jun 18 14:13:54 IST 2016
Since above is not working as expected so i tried DateFormat and its giving the expected result.
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
GregorianCalendar gc = dTime.toGregorianCalendar();
System.out.println(df.format(gc.getTime()));
Output: 2016-06-18 08:43:54 +0000
What could be the issue here as toGregorianCalendar(...) is not giving the desired result?
Also I noticed the GregorianCalendar instance obtained above from toGregorianCalendar has fieldSet= false. Not sure if this is causing the issue.
java.util.GregorianCalendar[time=1468382241000,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="UTC",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2016,MONTH=6,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=12,DAY_OF_YEAR=194,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=11,HOUR_OF_DAY=23,MINUTE=57,SECOND=21,MILLISECOND=0,ZONE_OFFSET=-14400000,DST_OFFSET=0]
Any help will be appreciated..!!

tl;dr
myPreparedStatement
.setObject( // Exchange java.time objects with your database in JDBC 4.2 and later.
… , // Specify which `?` placeholder in your SQL statement.
myXMLGregorianCalendar // A legacy class. Better to use *java.time* whenever possible.
.toGregorianCalendar() // Convert from the one legacy class to another, as a bridge towards the modern `ZonedDateTime` class.
.toZonedDateTime() // Convert to the modern class.
.toInstant() // Adjust from a time zone to UTC. Same moment, same point on the timeline, different wall-clock time.
.atOffset( // Adjust from basic `Instant` class to the more flexible `OffsetDateTime` class, if your JDBC driver does not offer the optional support for `Instant`.
ZoneOffset.UTC // Specify UTC using this constant.
) // Returns a `OffsetDateTime` object.
)
java.time
You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
convert the instance of XMLGregorianCalendar (which I got from JAXWS) to GregorianCalendar
First call XMLGregorianCalendar::toGregorianCalendar().
GregorianCalendar gc = myXMLGregorianCalendar.toGregorianCalendar() ;
Convert from the legacy class GregorianCalendar to the modern java.time.ZonedDateTime. Call the new conversion method added to the old class.
ZonedDateTime zdt = gc.toZonedDateTime() ;
date is coming in EST and I want to convert it into GMT
The java.time.Instant class represents a moment in UTC, always in UTC. You can extract an Instant from the ZonedDateTime. Same moment, different wall-clock time.
Instant instant = zdt.toInstant() ;
for further saving to DB
You may be able to pass an Instant to the database if your JDBC driver supports that. The Instant type is optional in JDBC 4.2.
myPreparedStatement.setObject( … , instant ) ;
If not supported, use OffsetDateTime as support is required by JDBC 4.2.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
The date is coming in EST
EST is not a real time zone.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-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" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;

Remember that Java Date objects don't have a time zone. They are internally in UTC. Time zone only manifests when printed (formatted).
This simple code works:
XMLGregorianCalendar xmlCal = XMLGregorianCalendarImpl.parse("2016-06-18T04:43:54-04:00");
GregorianCalendar cal = xmlCal.toGregorianCalendar();
java.util.Date date = cal.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(format.format(date)); // prints: 2016-06-18 08:43:54
Since your goal is to save it to a database, you really don't care about formatting it to text. Assuming you're using JDBC (not some NoSQL), you need a Timestamp.
XMLGregorianCalendar xmlCal = XMLGregorianCalendarImpl.parse("2016-06-18T04:43:54-04:00");
GregorianCalendar cal = xmlCal.toGregorianCalendar();
java.sql.Timestamp date = new java.sql.Timestamp(cal.getTimeInMillis());
Now you can give that to a PreparedStatement using setTimestamp().

I'm using the following code to convert an XMLGregorianCalendar from a given source with a given timezone (e.g. GMT+0) to a GregorianCalendar with the current system timezone :
GregorianCalendar.from(xmlGregorianCalendar
.toGregorianCalendar()
.toZonedDateTime()
.withZoneSameInstant(ZoneId.systemDefault()))
When you use only XMLGregorianCalendar.toGregorianCalendar(), the returned GregorianCalendar has the same timezone as the source system, not the timezone of the current system. Converting the timezone when you receive the data is safer: this way, you reduce the number of potential issues in your code because all dates are based on the system timezone.
For example:
XMLGregorianCalendar xmlGregorianCalendarFromSource = DatatypeFactory.newInstance()
.newXMLGregorianCalendar("1983-09-30T23:00:00.000Z"); // the source system is on GMT+0
GregorianCalendar gregorianCalendarWithSourceTZ = xmlGregorianCalendarFromSource.toGregorianCalendar();
GregorianCalendar gregorianCalendarWithSystemTZ = GregorianCalendar.from(xmlGregorianCalendarFromSource
.toGregorianCalendar()
.toZonedDateTime()
.withZoneSameInstant(ZoneId.systemDefault()));
System.out.println(xmlGregorianCalendarFromSource); // displays "1983-09-30T23:00:00.000Z" (i.e. GMT+0)
System.out.println(gregorianCalendarWithSourceTZ.toZonedDateTime()); // displays "1983-09-30T23:00Z[GMT]" (i.e. GMT+0)
System.out.println(gregorianCalendarWithSystemTZ.toZonedDateTime()); // displays "1983-10-01T00:00+01:00[Europe/Berlin]" (my system timezone is GMT+1 or GMT+2 depending on daylight saving)

As another route, you could consider using Date's instead of XMLGregorianCalendars in your code by using jaxb bindings as discussed in this stack overflow question.

Related

How to convert UTC to EST java.util.date in Java8+?

I have my code below which converts UTC to EST. But, how can I convert ZonedDateTime to java.util.Date from the below code along with this format (yyyy-MM-dd'T'HH:mm:ss) ?
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
String f = "yyyy-MM-dd'T'HH:mm:ss";
String timestamp = "2022-03-01T16:29:03"; //sample input
TemporalAccessor temporalAccessor = formatter.parse(timestamp);
LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
Instant result = Instant.from(zonedDateTime);
ZonedDateTime nyTime = result.atZone(ZoneId.of("Canada/Eastern"));
DateTimeFormatter format = DateTimeFormatter.ofPattern(f);
System.out.println("Date EST : " + format.format(nyTime));
Once you have ZonedDateTime in correct time zone convert it to Instant and then use method public static Date from(Instant instant) of class Date.
Instant instant = Instant.from(zonedDateTime);
Date date = Date.from(instant);
However, if you can, refrain from usage of Date class which is outdated (pun intended) package java.time with classes like ZonedDateTime, Instant
and others should be used
You commented:
I need to populate this in DB column. So I need to convert a string which is in UTC to EST then converting ZonedDateTime back to java.util.Date in this format (yyyy-MM-dd'T'HH:mm:ss)
Never use either Date class. Use only java.time classes. JDBC 4.2 and later supports java.time for exchanging date-time values with a database.
For a column of a type akin to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE, use java.time.LocalDateTime.
For a column of a type akin to the SQL-standard type TIMESTAMP WITH TIME ZONE, use java.time.OffsetDateTime.
Your input string:
String timestamp = "2022-03-01T16:29:03";
… is misnamed. That value lacks an indicator of time zone or offset-from-UTC. So it cannot represent a moment. We have no way of knowing if hat is around 4:30 PM in Tokyo Japan, or in Toulouse France, or in Toledo Ohio US — all very different moments several hours apart. So calling this a “timestamp” is misleading.
Parse that input string as a LocalDateTime. No need to specify a formatting pattern. That string complies with ISO 8691, used by default in the java.time classses when parsing/generating text.
LocalDateTime ldt = LocalDateTime.parse( "2022-03-01T16:29:03" ) ;
Your code at this point seems convoluted. You assign a default time zone to this date-with-time. But that seems unlikely to make sense. I am guessing that your intention was for this specific date-with-time to represent a specific moment as seen in a specific time zone.
Apparently you want eastern Canada 🇨🇦 time zone. The proper name for that zone is America/Toronto.
ZoneId z = ZoneId.of( "America/Toronto" ) ;
Assign that zone to produce a ZonedDateTime object.
ZonedDateTime zdt = ldt.atZone( z ) ;
Now we have a moment, a specific point on the timeline.
But for writing to a database column of a type akin to the SQL-standard TIMESTAMP WITH TIME ZONE, we need to use OffsetDateTime.
OffsetDateTime odt = zdt.toOffsetDateTime() ;
Later you commented that the input string is intended to represent a moment in UTC. So assign a ZoneOffset object, the constant UTC, to get an OffsetDateTime.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
Send to the database.
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
If you must use java.util.Date to interoperate with old code not yet updated to java.time, you can convert to and fro. Look to the new to… and from… methods added to the old classes.
java.util.Date d = Date.from( odt.toInstant() ) ;
java.util.Date d = Date.from( zdt.toInstant() ) ;
Going the other direction.
Instant instant = myJavaUtilDate.toInstant() ;
All of these topics have been addressed many times on Stack Overflow. Search to learn more.

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

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

What is the easiest way to get a formatted string from a calendar object which respects timezone?

When I search online about "how to convert a Calendar to a String", all the results I find suggest to first convert to a Date and then convert the Date to a String.
The problem is that a Date is only a representation of the number of milliseconds since the epoch - it does not respect timezone. Calendar is more advanced in this way.
Of course, I could call the individual Calendar.get methods to create my own formatted string, but surely there must be an easier way?
To illustrate, I wrote this code:
long currentTime = Calendar.getInstance().getTimeInMillis();
Calendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
calendar.setTimeInMillis(currentTime);
System.out.println(calendar.getTime().toString());
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime()));
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
While running this code from a machine based in London (UTC+0) at 8:02pm, I got the following results:
Wed Nov 18 20:02:26 UTC 2015
2015-11-18 20:02:26
21
The last line shows the real hour according to the calendar's timezone (Madrid which is UTC+1). It is 9:02pm in Madrid, but obviously both the native Date.toString as well as the DateFormat.format methods ignore the timezone because the timezone information is erased when calling Calendar.getTime (similarly Calendar.getTimeInMillis).
Given this, what is the best way to get a formatted string from a Calendar which respects timezone?
Set the timezone on the SimpleDateFormat object and then use z ..
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
System.out.println(sdf.format(calendar.getTime());
See here for details on how to handle timezones in Java.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
Calendar cal = Calendar.getInstance();
System.out.println(simpleDateFormat.format(cal.getTime()));
java.time
While the other Answers appear to be correct, a better approach is to avoid using java.util.Date/.Calendar entirely.
Those old date-time classes have been superseded by the java.time framework built into Java 8 and later. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
Instant
An Instant represents a moment on the timeline in UTC.
Instant instant = Instant.now ( ); // Current moment in UTC.
For a given Calendar object, convert to an Instant using the method toInstant added in Java 8.
Instant instant = myCalendar.toInstant();
ZonedDateTime
You can assign a time zone (ZoneId) to an Instant to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of ( "Europe/Madrid" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant, zoneId );
String Representation of Date-Time Value
Dump to console.
System.out.println ( "instant: " + instant + " adjusted into zone: " + zoneId + " is zdt: " + zdt );
The java.time classes use ISO 8601 standard formatting by default when parsing/generating String representations of date-time values. By default the ISO 8601 style is extended by appending the name of the time zone in addition to the usual offset-from-UTC.
instant: 2015-11-18T22:23:46.764Z adjusted into zone: Europe/Madrid is zdt: 2015-11-18T23:23:46.764+01:00[Europe/Madrid]
If you want the ISO 8601 style but without the T, either call .replace( "T" , "" ) on the resulting String object or define your own formatter.
The java.time.format package can do the work of determining a localized format appropriate to a particular Locale.
Locale locale = Locale.forLanguageTag ( "es-ES" );
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL );
String output = zdt.format ( formatter.withLocale ( locale ) );
miércoles 18 de noviembre de 2015 23H38' CET
You can use String.format() to avoid timezone problems
http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
This example gives a result in the format: "yyyy-MM-dd HH:mm:ss"
Calendar c = Calendar.getInstance();
String s = String.format("%1$tY-%1$tm-%1$td:%1$tM:%1$tS", c);
System.out.println(s);
Output:
2015-11-20:44:55

how to convert Date Object to given from UTC to any time zone like IST,WAST

i am so confuse how to do that i have a database date in UTC i want to convert in any given format by user kile IST ,WAST,CST . Iwant to know how can i do so.I am passing the zone value which is given by client here is my code :
for getting value from client i am using this:
var localTimeZone = new Date().getTimezone();
after that i want to a method which have three parameter
targetTimeFromZone(Date date, String fromTZ, String toTZ);
where fromTZ="UTC" and toTZ = "IST" or CST or any of time Zone.
Avoid java.util.Date and .Calendar as they are notoriously troublesome. Use either Joda-Time or the java.time package in Java 8.
Per Jon Skeet's comment, avoid 3 or 4 letter time zone codes as they are neither standardized nor unique. Use proper time zone names.
A DateTime in Joda-Time knows its own assigned time zone, unlike j.u.Date.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" ); // or get the default time zone.
Convert a Date to DateTime.
java.util.Date someDate = new java.util.Date(); // As if we were passed a Date.
DateTime dateTime = new DateTime( someDate, timeZone );
Adjust time zone.
DateTime dateTimeMontréal = dateTime.withZone( DateTimeZone.forID( "America/Montreal" ) );
DateTime dateTimeUtc = dateTime.withZone( DateTimeZone.UTC );
If required by other classes, generate a java.util.Date object.
java.util.Date date = dateTime.toDate();
Search StackOverflow for many more examples and discussion.

Date format conversion as a Date object in a particular format in java

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());

Categories