SUM days to the DB date [duplicate] - java

This question already has answers here:
"cannot find symbol: method" but the method is declared
(3 answers)
How to add one day to a date? [duplicate]
(18 answers)
Closed 3 years ago.
When I try to add 30 days with the date obtained in the Database is giving this error.
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date today = Calendar.getInstance().getTime();
String reportDate = df.format(today);
String endDay = rset.getString("vip_end");
endDay.add(Calendar.DAY_OF_MONTH, 30)
Error
Error:(76, 70) java: cannot find symbol
symbol: method add(int,int)
location: variable endDay of type java.lang.String

tl;dr
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.now( // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Asia/Tokyo" ) // Specify your time zone. Use proper `Continent/Region` names, never 2-4 character pseudo-zones such as IST or PST or EST or CST.
) // Returns a `LocalDate` object.
.plusDays( 30 ) // Add days to determine a later date. Returns a new `LocalDate` object rather than mutating the original.
.toString() // Generate text representing the value of this `LocalDate` object, in standard ISO 8601 format YYYY-MM-DD.
2019-06-30
No add method on String
You declared endDay to be a String. Then you called the method add. But there is no method add on String class. Thus your error, as explained in the error message.
java.time
You are using terrible date-time classes that were supplanted years ago by the modern java.time classes with the adoption of JSR 310. Stop doing that.
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
Time zone
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 during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.
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" ) ;
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 code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
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. Ditto for Year & YearMonth.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Generating text
Your output format is in standard ISO 8601 format. This format is used by default in the LocalDate class for parsing/generating strings. So no need to specify a formatting pattern.
String output = LocalDate.of( 2019 , Month.JANUARY , 23 ).toString() ;
2019-01-23
Date math
Add 30 days.
LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDate later = today.plusDays( 30 ) ;
The java.time classes follow the immutable objects pattern. So they return a new fresh object based on the values of the original.

Related

How to add HH:MM:SS format to the LocalDate in java?

LocalDate beginDate = LocalDate.now()
.with(ChronoField.DAY_OF_WEEK, 1)
.atStartOfDay()
.minusDays(8)
.toLocalDate();
I am getting the previous week begin date using the above code line. However I want to add HH:MM:SS format to this. I have tried different ways to get this. Tried using LocalDateTime instead of Localdate. But could not find atStartOfDay() method for LocalDateTime. Help me to add HH:MM:SS to beginDate variable
tl;dr
LocalDate // Represents a date only, without a time of day, without a time zone or offset.
.now( ZoneId.of( "Asia/Amman" ) ) // Returns a `LocalDate`.
.minusDays( 8 ) // Returns another `LocalDate` object.
.atStartOfDay( ZoneId.of( "Asia/Amman" ) ) // Returns a `ZonedDateTime`.
.toString() // Returns a `String` object, with text in standard ISO 8601 format wisely extended to append the name of time zone in brackets.
See this code run at Ideone.com. Notice that on that date in that zone, the day began at 01:00, not 00:00.
2022-02-22T01:00+03:00[Asia/Amman]
No “format” involved
Date-time objects do not have a “format”. Text has a format. Date-time objects are not text.
LocalDate has no time of day
You said:
add HH:MM:SS format to [a LocalDate object]
A LocalDate represents a date only, without a time of day, without a time zone or offset.
ZonedDateTime
Apparently you want the first moment of the day eight days ago as seen in your locality.
First, specify your desired/expected time zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
Or use your JVM‘s current default time zone.
ZoneId z = ZoneId.systemDefault() ;
Capture the current date as seen in that zone.
LocalDate today = LocalDate.now( z ) ;
Go back eight days.
LocalDate eightDaysAgo = today.minusDays( 8 ) ;
If you meant to go back to the previous Monday, use a TemporalAdjuster.
LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) ) ;
Get the first moment of that day. Pass your time zone.
ZonedDateTime zdt = eightDaysAgo.atStartOfDay( z ) ;
The time-of-day may be 00:00:00, but not necessarily. Some days on some dates in some zones start at another time such as 01:00:00.
All of this has been covered many times already on Stack Overflow. Search to learn more.
What you want is a LocalDateTime, which is a LocalDate with a time component (including timezone).
LocalDate does as it says on the tin, it gives you a date, not a date and time.
LocalDateTime
.of(LocalDate.now().with(ChronoField.DAY_OF_WEEK, 1), LocalTime.MIDNIGHT)
.minusWeeks(1)
Gives you start of last week at midnight (local time).
#DateTimeFormat("HH:MM:SS")
#JsonFormat("HH:MM:SS")

Scala - java.sql.Date is parsed incorrectly when collecting distinct values from a DataSet

I'm parsing dates from a Dataset[Transaction] objects in order to collect a set of dictinct values:
val distinctTransactionDates: Set[Date] = transactions.map(t => t.transaction_date).distinct().collect().toSet
But the dates are parsed incorrectly, for example if a transaction's Date is 2019-03-31, the returned value is 2019-04-01. When I logged to check t.transaction_date.getTime it is 1553990400000 (GMT: Sunday, 31 Mar 2019, 0:00:00). But the gap for some dates vs getTime is more than one day.
The Date here is a java.sql.Date
I can't figure out how to parse dates correctly in this case in order to get distinct values without any corrections. For the above example I'm expecting to get 2019-03-31.
You are trying to extract a date-only value from a date-with-time-of-day source, but failing to account for time zone.
Another problem: You are using the terrible java.sql.Date class that was supplanted years ago by the modern java.time classes. Specifically, LocalDate.
Your date-with-time-of-day source can be referred to as a moment, a specific point on the timeline. For any given moment the time-of-day and the date both vary by time zone around the globe. Noon in Paris is not noon in Montréal. And a new day dawns earlier in the east than in the west. You must get very clear on this to do proper date-time handling. One moment in nature can be viewed in many ways through human-created notions of time zones.
First extract your moment via JDBC as an OffsetDateTime object.
Code shown here is in Java syntax rather than Scala. Also, note that java.time uses immutable objects.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Adjust into the time zone by which you want to perceive a date.
ZoneId z = ZoneId( "Asia/Tokyo" ) ;
ZonedDateTime zdt = odt.withZoneSameInstant( z ) ;
Extract the date-only portion.
LocalDate ld = zdt.toLocalDate() ;

java8 ZonedDateTime doesnt print EST current time. What am I doing wrong here

below is the code I have to print out the current EST date time, but it prints out time in my Time zone which is Arizona Time. What am I missing in this code. Thankyou!
public static void main(String args[]) {
LocalDateTime datetime = LocalDateTime .now();
ZonedDateTime zdtNewYork = ZonedDateTime.of ( datetime , ZoneId.of ( "America/New_York" ) );
System.out.println(zdtNewYork.format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss.SSS")));
}
tl;dr
You captured Arizona date and time-of-day, then slapped on a time zone to claim (incorrectly) that New York has the same time-of-day at that moment.
So of course when you generated text to display these values, you saw the time-of-day first captured in Arizona. At no point did you adjust from Arizona to New York.
LocalDateTime is the wrong class
Never use LocalDateTime for tracking moments. By definition, that class cannot represent a specific moment in time, a point on the timeline. It holds a date and time-of-day but lacks the context of a time zone or offset-from-UTC. Telling us "Noon on the 23rd of January this year" is meaningless if we do not know whether you meant noon in Tokyo Japan, Kolkata India, Paris France, or Montréal Québec — all very different moments, hours apart.
Always specify time zone
To compound on using the wrong class, you called LocalDateTime.now without specifying the time zone. So your JVM’s current default time zone was implicitly applied. You claim that default is some time zone in Arizona. So that would be zone applied.
So, you captured the date & time-of-day as seen in Arizona. But then you discarded the fact that the value was in Arizona time zone, because of your use of LocalDateTime. Discarding the time zone is the entire point of the LocalDateTime class. There are cases where that is useful, but certainly not in your situation.
You then took that Arizona date & time-of-day, and claimed that was the date and time in New York. The actual time-of-day in New York was hours ahead of that, so you told a fib. Lastly you generated text showing that fib.
In other words, apparently you thought this line:
ZonedDateTime.of ( datetime , ZoneId.of ( "America/New_York" ) )
…adjusted from Arizona to New York. But that datetime argument no longer knows it came from Arizona, because LocalDateTime has no concept of zone/offset. No adjustment was made.
You can think of it this way:
LocalDateTime = date + time-of-day
OffsetDateTime = date + time-of-day + offset
ZonedDateTime = date + time-of-day + zone
Instant = date + time-of-day + UTC
Instead, I recommend always specifying explicitly your desired/expected time zone. Even if you want the current default time zone, say so explicitly by calling ZoneId.systemDefault so any programmer reading your code knows your intention clearly. Letting the time zone or offset-from-UTC be optional is one of the few things I would change in the otherwise amazing class design found in java.time. Making the zone/offset arguments required would help to educate more programmers about date-time handling.
ZonedDateTime is the right class
To represent a moment as seen through the wall-clock time used by the people of a particular region (a time zone), use ZonedDateTime.
ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
See this code run live at IdeOne.com.
zdt.toString(): 2019-03-04T18:17:08.014-05:00[America/New_York]
Generate text
We can generate the text you want easily.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss.SSS" ) ;
String output = zdt.format( f ) ;
See this code run live at IdeOne.com.
03/04/2019 18:17:08.014
Adjusting zones
If you do want to adjust between zones, call the ZonedDateTime::withZoneSameInstant method.
ZonedDateTime zdtPhoenix = ZoneDateTime.now( ZoneId.of( "America/Phoenix" ) ) ;
ZonedDateTime zdtNewYork = zdtPhoenix.withZoneSameInstant( ZoneId.of( "America/New_York" ) ) ; // Same moment, same point on the timeline, different wall-clock time.
Notice the phrase SameInstant that means you want the same moment, the same simultaneous point on the timeline, but you want to see it through the wall-clock time used by the people of the New York region.
Time zones
print out the current EST date time
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use or refer to the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
Try something like:
LocalDateTime datetime = LocalDateTime .now(ZoneId.of ( "America/New_York" ));
System.out.println(datetime.format(DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss.SSS")));

How to convert UTC and local timezone in Java

I am curious about timezone in Java. I want to get UTC time in milliseconds from a device and send to server. Server will convert it to local timezone when it displays time to users. Timezone in my system is Australia/Sydney( UTC + 11:00), and I have got the result below when I tested timezone:
int year = 2014;
int month = 0;
int date = 14;
int hourOfDay = 11;
int minute = 12;
int second = 0;
Calendar c1 = Calendar.getInstance();
c1.set(year, month, date, hourOfDay, minute, second);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss z");
System.out.println(sdf.format(c1.getTime()));
Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c2.set(year, month, date, hourOfDay, minute, second);
System.out.println(sdf.format(c2.getTime()));
output:
14/01/2014 11:12:00 EST
14/01/2014 22:12:00 EST
I thought I could have 13/01/2014 00:12:00 for c2 because UTC time is 11 hours later than mine. Does not Calendar work the way I expect?
Your help would be appreciated.
EDIT
Added z to display timezone. This makes me more confused because Mac says its timezone is (AEDT) Australian Eastern Daylight Time but Java is EST. Anyway still result is different because EST is UTC-5 hours.
UPDATE: This Answer is now out-of-date. The Joda-Time library is now supplanted by the java.time framework built into Java 8 and later. See this new Answer.
Three-Letter Codes
You should avoid using 3 or 4 letter time zone codes such as EST or IST. They are neither standard nor unique.
Use proper time zone names, mostly Continent/CityOrRegion such as America/Montreal or Asia/Kolkata.
Joda-Time
The java.util.Date/Calendar classes are notoriously bad. Avoid using them. Use either Joda-Time or, in Java 8, the new java.time.* classes defined by JSR 310 and inspired by Joda-Time.
Notice how much simpler and more obvious is the Joda-Time code shown below. Joda-Time even knows how to count – January is 1, not 0!
Time Zone
In Joda-Time, a DateTime instance knows its own time zone.
Sydney Australia has a standard time of 10 hours ahead of UTC/GMT, and a Daylight Saving Time (DST) of 11 hours ahead. DST applies to the date specified by the question.
Tip: Don't think like this…
UTC time is 11 hours later than mine
Think like this…
Sydney DST is 11 hours ahead of UTC/GMT.
Date-time work becomes easier and less error-prone if you think, work, and store in UTC/GMT. Only convert to localized date-time for presentation in the user-interface. Think globally, display locally. Your users and your servers can easily move to other time zones, so forget about your own time zone. Always specify a time zone, never assume or rely on default.
Example Code
Here is some example code using Joda-Time 2.3 and Java 8.
// Better to specify a time zone explicitly than rely on default.
// Use time zone names, not 3-letter codes.
// This list is not quite up-to-date (read page for details): http://joda-time.sourceforge.net/timezones.html
DateTimeZone timeZone = DateTimeZone.forID("Australia/Sydney");
DateTime dateTime = new DateTime(2014, 1, 14, 11, 12, 0, timeZone);
DateTime dateTimeUtc = dateTime.toDateTime(DateTimeZone.UTC); // Built-in constant for UTC (no time zone offset).
Dump to console…
System.out.println("dateTime: " + dateTime);
System.out.println("dateTimeUtc: " + dateTimeUtc);
When run…
dateTime: 2014-01-14T11:12:00.000+11:00
dateTime in UTC: 2014-01-14T00:12:00.000Z
You probably meant to set the timezone on your formatter, not the Calendar (or in addition the the Calendar, it is not 100% clear what you mean to accomplish)! The timezone used to create the human representation comes from the SimpleDateFormat. All "timezone" information is lost from the Calendar when you convert it back into a java.util.Date by calling getTime().
The code:
Calendar c2 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c2.set(year, month, date, hourOfDay, minute, second);
System.out.println(sdf.format(c2.getTime()));
is printing 14/01/2014 10:12:00 because 11AM UTC displayed in Syndey (the timezone of your formatter) is 10PM! (use HH in the format for 24 hour time)
This would print what it seems like you meant to do:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss z");
System.out.println(sdf.format(c1.getTime()));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(c1.getTime()));
The concept of 'UTC milliseconds' is meaningless. A quantity of milliseconds is just a fixed point in history, it has no timezone associated with it. We add a timezone to it to convert it into human-readable representations.
edit: Yes, the ambiguity of using 'EST' for both (US) Eastern Time and (Australian) Eastern Time has been a pitfall in Java since forever.
tl;dr
Use modern java.time classes.
ZonedDateTime
.of( 2014 , 1 , 14 , 11 , 12 , 0 , 0 , ZoneId.of( "Australia/Sydney" ) )
.toInstant()
.toEpochMilli()
1389658320000
Going the other direction.
Instant
.ofEpochMilli( 1_389_658_320_000L ) // .toString(): 2014-01-14T00:12:00Z
.atZone(
ZoneId.of( "Australia/Sydney" )
) // .toString(): 2014-01-14T11:12+11:00[Australia/Sydney]
.format(
DateTimeFormatter
.ofPattern (
"dd/MM/uuuu HH:mm:ss z" ,
new Locale( "en" , "AU" )
)
)
14/01/2014 11:12:00 AEDT
java.time
You are using terrible date-time classes that were made obsolete years ago by the adoption of JSR 310 defining the modern java.time classes.
I am curious about timezone in Java.
FYI, an offset-from-UTC is merely a number of hours-minutes-seconds. When we say “UTC” or put a Z at the end of a string, we mean an offset of zero hours-minutes-seconds, for UTC itself.
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. Politicians around the world have an odd penchant for changing the offset of their jurisdiction.
I want to get UTC time in milliseconds from a device and send to server.
For the current moment, use Instant. An Instant internally is the number of whole seconds seconds since the epoch reference of first moment of 1970 UTC, plus a fraction of a second in nanoseconds.
Instant now = Instant.now() ; // Capture current moment in UTC.
long millisecondsSinceEpoch = now.toEpochMilli() ;
Going the other direction.
Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch ) ;
Server will convert it to local timezone …
Specify the time zone desired/expected by the user.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.
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 = instant.atZone( z ) ;
… when it displays time to users
Automatically localize for the user's language and culture.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.JAPAN, etc.
DateTimeFormatter f =
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( l )
;
String output = zdt.format( f );
Timezone in my system is Australia/Sydney( UTC + 11:00)
The current default time zone of your server should be irrelevant to your program. Always specify the desired/expected time zone. Frankly, making optional the time zone (and Locale) argument of the various date-time methods is one of the very few design flaws in java.time framework.
Tip: Generally best to set your servers to UTC as their current default time zone.
By the way, be clear that time zone and locale have nothing to do with one another. You might want Japanese language for displaying a moment as seen in Africa/Tunis time zone.
ZoneID zAuSydney = ZoneId.of( "Australia/Sydney" ) ;
ZonedDateTime zdt = instant.atZone( zAuSydney ) ;
String output = zdt.format(
DateTimeFormatter
.localizedDateTime( FormatStyle.LONG )
.withLocale( new Locale( "en" , "AU" ) ;
) ;
int year = 2014; …
Note that java.time uses sane numbering, unlike the legacy classes. Months are 1-12 for January-December, and weekdays are 1-7 for Monday-Sunday.
LocalDate ld = LocalDate.of( 2014 , 1 , 14 ) ;
LocalTime lt = LocalTime.of( 11 , 12 ) ;
ZoneId z = ZoneId.of( "Australia/Sydney" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
zdt.toString() = 2014-01-14T11:12+11:00[Australia/Sydney]
Generally best to automatically localize for display, as seen above. But if you insist, you can hard-code a formatting pattern.
Locale locale = new Locale ( "en" , "AU" );
ZoneId z = ZoneId.of ( "Australia/Sydney" );
ZonedDateTime zdt = ZonedDateTime.of ( 2014 , 1 , 14 , 11 , 12 , 0 , 0 , z );
zdt.toString(): 2014-01-14T11:12+11:00[Australia/Sydney]
Specify that formatting pattern of yours.
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd/MM/uuuu HH:mm:ss z" , locale );
String output = zdt.format ( f );
output = 14/01/2014 11:12:00 AEDT
Your Question was interested in a count of milliseconds since epoch of 1970-01-01T00:00:00Z. So adjust from the Australia time zone to UTC. Same moment, same point on the timeline, different wall-clock time.
Instant instant = zdt.toInstant() ; // Adjust from time zone to UTC.
instant.toString(): 2014-01-14T00:12:00Z
Note the difference in hour-of-day between instant and zdt.
I thought I could have 13/01/2014 00:12:00 for c2 because UTC time is 11 hours later than mine.
➥ As you asked for, twelve minutes after 11 AM in Sydney zone is the same moment as twelve minutes after midnight in UTC, because Australia/Sydney on that date is eleven hours ahead of UTC.
Calculate milliseconds since epoch.
long millisecondsSinceEpoch = instant.toEpochMilli() ;
here is the output result you need to check this out
final String time="UTC";
int year = 2014;
int month = 0;
int date = 14;
int hourOfDay = 11;
int minute = 12;
int second = 0;
calendar.set(year, month, date, hourOfDay, minute, second);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz");
System.out.println(sdf.format(calendar.getTime()));
Calendar calendar1=Calendar.getInstance();
Date dat= calendar.getTime();
calendar1.set(year,month,date,hourOfDay,minute,second);
sdf.setTimeZone(TimeZone.getTimeZone(time));
System.out.println(sdf.format(calendar1.getTime()));

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