How to convert TimeStamp to Date in Java? - java

How do I convert 'timeStamp' to date after I get the count in Java?
My current code is as follows:
public class GetCurrentDateTime {
public int data() {
int count = 0;
java.sql.Timestamp timeStamp = new Timestamp(System.currentTimeMillis());
java.sql.Date date = new java.sql.Date(timeStamp.getTime());
System.out.println(date);
//count++;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/pro", "root", "");
PreparedStatement statement = con.prepareStatement("select * from orders where status='Q' AND date=CURDATE()");
ResultSet result = statement.executeQuery();
while (result.next()) {
// Do something with the row returned.
count++; //if the first col is a count.
}
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
return count;
}
}
This is my database:
Here the output I got was 2012-08-07 0, but the equivalent query returns 3. Why do I get 0?

Just make a new Date object with the stamp's getTime() value as a parameter.
Here's an example (I use an example timestamp of the current time):
Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
System.out.println(date);

// timestamp to Date
long timestamp = 5607059900000; //Example -> in ms
Date d = new Date(timestamp );
// Date to timestamp
long timestamp = d.getTime();
//If you want the current timestamp :
Calendar c = Calendar.getInstance();
long timestamp = c.getTimeInMillis();

Just:
Timestamp timestamp = new Timestamp(long);
Date date = new Date(timestamp.getTime());

I have been looking for this since a long time, turns out that Eposh converter does it easily:
long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000;
Or the opposite:
String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));

tl;dr
LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) )
.toEpochSecond()
…
LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
.plusDays( 1 )
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) )
.toEpochSecond()
…
"SELECT * FROM orders WHERE placed >= ? AND placed < ? ; "
…
myPreparedStatement.setObject( 1 , start )
myPreparedStatement.setObject( 2 , stop )
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the modern java.time classes.
Apparently you are storing a moment in your database in a column of some integer type. That is unfortunate. You should instead be using a column of a type such as the SQL-standard TIMESTAMP WITH TIME ZONE. But, for this Answer, we will work with what we have.
If your records represent moments with a resolution of milliseconds, and you want all the records for an entire day, then we need a time range. We must have a start moment and a stop moment. Your query has only a single date-time criterion where it should have had a pair.
The LocalDate class represents a date-only value without time-of-day and without 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, 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 ) ;
With a LocalDate in hand, we next need to transform that into a pair of moment, the start and stop of the day. Do not assume the day starts at 00:00:00 time-of-day. Because of anomalies such as Daylight Saving Time (DST), the day may start at another time such as 01:00:00. So let java.time determine the first moment of the day. We pass a ZoneId argument to LocalDate::atStartOfDay to look up any such anomalies. The result is a ZonedDateTime.
ZonedDateTime zdtStart = ld.atStartOfDay( z ) ;
Generally the best approach to defining a span of time is the Half-Open approach where the beginning is inclusive while the ending is exclusive. So a day starts with its first moment and runs up to, but not including, the first moment of the next day.
ZonedDateTime zdtStop = ld.plusDays( 1 ).atStartOfDay( z ) ; // Determine the following date, and ask for the first moment of that day.
Our query for an entire day cannot make use of SQL command BETWEEN. That command is Fully-Closed ([]) (both beginning and ending are inclusive) where as we want Half-Open ([)). We use a pair of criteria >= and <.
Your column is poorly named. Avoid any of the thousand words reserved by various databases. Let’s use placed in this example.
Your code should have used ? placeholders in which to specify our moments.
String sql = "SELECT * FROM orders WHERE placed >= ? AND placed < ? ; " ;
But we have ZonedDateTime objects in hand, while your database apparently is storing integers as discussed above. If you had defined your column properly we could simply pass the ZonedDateTime objects with any JDBC driver supporting JDBC 4.2 or later.
But instead we need to get a count-from-epoch in whole seconds. I will assume your epoch reference date is the first moment of 1970 in UTC. Beware of possible data loss, as the ZonedDateTime class is capable of nanosecond resolution. Any fractional second will be truncated in the following lines.
long start = zdtStart().toEpochSecond() ; // Transform to a count of whole seconds since 1970-01-01T00:00:00Z.
long stop = zdtStop().toEpochSecond() ;
Now we are ready to pass those integers to our SQL code defined above.
PreparedStatement ps = con.prepareStatement( sql );
ps.setObject( 1 , start ) ;
ps.setObject( 2 , stop ) ;
ResultSet rs = ps.executeQuery();
When you retrieve your integer values from the ResultSet, you can transform into Instant objects (always in UTC), or into ZonedDateTime objects (with an assigned time zone).
Instant instant = rs.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.
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, 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.

try to use this java code :
Timestamp stamp = new Timestamp(System.currentTimeMillis());
Date date = new Date(stamp.getTime());
DateFormat f = new SimpleDateFormat("yyyy-MM-dd");
DateFormat f1 = new SimpleDateFormat("yyyy/MM/dd");
String d = f.format(date);
String d1 = f1.format(date);
System.out.println(d);
System.out.println(d1);

First of all, you're not leveraging the advantage of using a PreparedStatement. I would first suggest that you modify your PreparedStatement as follows:
PreparedStatement statement = con.prepareStatement("select * from orders where status=? AND date=?")
You can then use statement.setXX(param_index, param_value) to set the respective values. For conversion to timestamp, have a look at the following javadocs:
PreparedStatement.setTimeStamp()
Timestamp
Hope this helps!

In Android its very Simple .Just use the Calender class to get currentTimeMillis.
Timestamp stamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
Date date = new Date(stamp.getTime());
Log.d("Current date Time is " +date.toString());
In Java just Use System.currentTimeMillis() to get current timestamp

Not sure what you're trying to select in the query, but keep in mind that UNIX_TIMESTAMP() without arguments returns the time now. You should probably provide a valid time as argument, or change the condition.
EDIT:
Here is an example of a time bound query based on the question:
PreparedStatement statement = con
.prepareStatement("select * from orders where status='Q' AND date > ?");
Date date = new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2000");
statement.setDate(1, new java.sql.Date(date.getTime()));
EDIT: timestamp column
In case of timestamp use java.sql.Timestamp and PreparedStatement.setTimestamp(), ie:
PreparedStatement statement = con
.prepareStatement("select * from orders where status='Q' AND date > ?");
Date date = new SimpleDateFormat("dd/MM/yyyy").parse("01/01/2000");
Timestamp timestamp = new Timestamp(date.getTime());
statement.setTimestamp(1, timestamp);

new Date(timestamp.getTime()) should work, but the new fancy Java 8 way (which may be more elegant and more type safe, as well as help lead you to use the new time classes) is to call Date.from(timestamp.toInstant()).
(Do not rely on the fact that Timestamp itself is an instance of Date; see explanation in the comments of another answer .)

Timestamp tsp = new Timestamp(System.currentTimeMillis());
java.util.Date dateformat = new java.util.Date(tsp.getTime());

I feel obliged to respond since other answers seem to be time zone agnostic which a real world application cannot afford to be. To make timestamp-to-date conversion correct when the timestamp and the JVM are using different time zones you can use Joda Time's LocalDateTime (or LocalDateTime in Java8) like this:
Timestamp timestamp = resultSet.getTimestamp("time_column");
LocalDateTime localDateTime = new LocalDateTime(timestamp);
Date trueDate = localDateTime.toDate(DateTimeZone.UTC.toTimeZone());
The example below assumes that the timestamp is UTC (as is usually the case with databases). In case your timestamps are in different timezone, change the timezone parameter of the toDatestatement.

Assuming you have a pre-existing java.util.Date date:
Timestamp timestamp = new Timestamp(long);
date.setTime( l_timestamp.getTime() );

You can use this method to get Date from Timestamp and Time-zone of particular area.
public String getDayOfTimestamp(long yourLinuxTimestamp, String timeZone) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(yourLinuxTimestamp * 1000);
cal.setTimeZone(TimeZone.getTimeZone(timeZone));
Date date = cal.getTime();
}

String timestamp="";
Date temp=null;
try {
temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(getDateCurrentTimeZone(Long.parseLong(timestamp)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int dayMonth=temp.getDate();
int dayWeek=temp.getDay();
int hour=temp.getHours();
int minute=temp.getMinutes();
int month=temp.getMonth()+1;
int year=temp.getYear()+1900;

import java.sql.Timestamp
new Timestamp(1234567890123L)
// java.sql.Timestamp = 2009-02-14 10:31:30.123
(new Timestamp(1234567890123L)).toLocalDateTime().toLocalDate().toString()
// 2009-02-14
What is a different result from one of the previous most voted answers:
import java.time.format.DateTimeFormatter
import java.time.ZoneId
import java.time.ZoneOffset
(DateTimeFormatter.ISO_LOCAL_DATE).withZone(ZoneId.from(ZoneOffset.UTC)).format(new Timestamp(1234567890123L).toInstant())
// String = 2009-02-13
In my case, I was expecting the "2009-02-14" instead of the "2009-02-13". So the top result worked better for me.

Date updated = timestamp.toDate();

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date fecha = getDateInTimestamp();

Related

How to check validity of Java date type?

I wrote two simple functions to get the value of my date in MySQL table. Both start date and end date columns are both Date data type. So, in my these two function that goes something like this:
public Date get_startdate(long nodeid,String ts) {
try {
String sql="Select STARTDT FROM urllink WHERE URL='f0="+nodeid+"&ts="+ts + "'";
if (em == null) {
throw new Exception("could not found URL object.");
}
return (Date) em.createNativeQuery(sql).getSingleResult();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Date get_enddate(long nodeid,String ts) {
try {
String sql="Select ENDDT FROM urllink WHERE URL='f0="+nodeid+"&ts="+ts + "'";
if (em == null) {
throw new Exception("could not found URL object.");
}
return (Date) em.createNativeQuery(sql).getSingleResult();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Now that I call these functions in my main page like these, I want to check the date conditions that if the URL is between these two dates,then it should be valid and do something. I highlight what I mean below:
Date file_getstartdate=fileFacade1.get_startdate(fileID,hash);
Date file_getenddate=fileFacade1.get_enddate(fileID,hash);
String currentDate = CoreUtil.parseDate(new Date());
if( file_getstartdate<= currentDate<= file_getendDate){
//URL is valid, do something
}else {
//do nothing
}
My date stored in my table is in the format YYYY-MM-DD and the problem I am facing is in the if statement above to make the comparison.I can't use those operators to do the checking. Is there a way to achieve what I desire?
Don't use String concatenation to construct SQL queries
This is vulnerable to SQL injection, and is really dangerous:
String sql="Select STARTDT FROM urllink WHERE URL='f0="+nodeid+"&ts="+ts + "'";
...
return (Date) em.createNativeQuery(sql).getSingleResult();
Assuming em refers to an EntityManager object then you can build a Criteria based query, or if you really need to stick with native SQL then you should use a PreparedStatement instead.
For your comparison question, you have three issues:
You're trying to compare two different types (String and Date).
You're trying to use an operator that can only be used to compare primitives but not Objects (<=).
You're writing your condition like a mathematical statement instead of a programming conditional statement (a <= b <= c isn't a valid Java statement. It needs to be a <= b && b <= c).
Here is a way to compare using the Date class (note that since Java 8 LocalDate is a much better class to use if you have the option).
Date fileStartDate = fileFacade1.get_startdate(fileID, hash);
Date fileEndDate = fileFacade1.get_enddate(fileID, hash);
Date currentDate = new Date();
if (fileStartDate.before(currentDate) && fileEndDate.after(currentDate) {
...
In response to your comment
Okay but does using preparedStatement helps with this SQL inejction. Does entity manager prevent the injection? I was told not to use preparedstatement,are there any other alternatives?
If someone told you to make a native query using string concatenation (the +nodeid+ and +ts + parts of your code) instead of using a PreparedStatement then they are wrong. An EntityManager will not protect you from injection in the code above, but a PreparedStatement, along with changing how your query is constructed, would.
A PreparedStatement would look something like
String url = "f0=" + nodeid + "&ts=" + ts;
PreparedStatement preparedStatement = connection.prepareStatement("Select STARTDT FROM urllink WHERE URL= ?");
preparedStatement.setString(1, url);
ResultSet resultSet = preparedStatement.executeQuery();
If you've been told to use an EntityManager instead of writing native SQL then that's actually good advice. You'll need to construct your query using the Criteria abstraction. How to do that is probably a separate question.
If you use strings instead of date objects, that if statement will work for that format, assuming you write it like (a <= b && b <= c)
Otherwise, I'm not sure how getSingleResult() can be cast into a Date object, as that could be anything, and you'd actually have to parse the value, then use proper Date methods to check isBefore and isAfter
Java: how do I check if a Date is within a certain range?
tl;dr
if( file_getstartdate<= currentDate<= file_getendDate) { … }
LocalDateRange // Represent a span-of-time as a pair of `LocalDate` (date-only) objects.
.ofClosed( startLocalDate , stopLocalDate ) // Making the date range in fully-closed approach, against my advice of using half-open approach.
.contains( // Compares a specified `LocalDate` against the start and stop dates of the range.
LocalDate.now( // Use `java.time.LocalDate` to represent a date-only value without a time-of-day and without a time zone.
ZoneId.of( "Africa/Tunis" ) // Specify the time zone by which we want to perceive the calendar date for the current moment. "Tomorrow" arrives in Paris France while still "yesterday" in Montréal Québec.
) // Returns a `LocalDate` object.
) // Returns a `boolean` primitive.
java.time
The Answer by Player One is correct, but can be improved by using the modern java.time classes rather than the terrible legacy classes (Date, etc.).
LocalDate
For a column of type SQL-standard DATE, use the LocalDate class. 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.
ZoneID
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.
Half-Open
if( file_getstartdate<= currentDate<= file_getendDate){
You will find your work easier if you consistently use the Half-Open approach to defining a span-of-time. In this approach, the beginning is inclusive while the ending is exclusive. So a month starts on the first and runs up to, but does not include, the first of the following month.
So your query logic would be, like the following, with <= & <.
if( file_getstartdate <= currentDate < file_getendDate)
This means in SQL, do not use BETWEEN for date-time work.
String sql = "SELECT * from tbl WHERE when >= ? AND when < ? ;" ;
…
myPreparedStatement.setObject( 1 , today ) ;
myPreparedStatement.setObject( 2 , today ) ;
To retrieve DATE, values:
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
The same kind of half-open logic within Java code would look like the following code. Note that a shorter way of saying "is equal to or is later than" is "is not before".
boolean isTodayWithinDateRange =
( ! today.isBefore( startDate ) ) // Is today same or later than start…
&& // AND
today.isBefore( stopDate ) // Is today before the stop (for Half-Open approach).
;
Do not conflate date-time values with text
My date stored in my table is in the format YYYY-MM-DD
No it is not. The DATE type in MySQL stores a date by its own internally-defined mechanism, not plain text.
A date-time object such as DATE column in database or LocalDate in Java can parse a string input into a date value, and can generate a string from that date value. But the date value is not itself string. Do not confuse the two. In other words, a date value does not have “format”, only their textual representations have a format.
LocalDateRange
If doing much of this work, add the ThreeTen-Extra library to your project. This gives you access to the LocalDateRange class.
LocalDate start = … ;
LocalDate stop = … ;
LocalDateRange range = LocalDateRange.of( start , stop ) ;
boolean rangeContainsToday = range.contains( today ) ;
By default the LocalDateRange class works using Half-Open approach. But if you insist on your full-closed approach, override its default behavior with LocalDateRange.ofClosed method.
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….
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.

Saving and retrieving Date in GMT timezone and converting to String

I have a requirement to
Save and retrieve the date in GMT timezone (date should be converted to String). So, if user saves date 10/10/2017 23:05, that will be saved as 10/11/2017 4:05 (5 hours ahead if saved in CST time for e.g.) in DB.
While retrieving and presenting the date to UI, it should show as 10/10/2017 23:05 for CST users.
Also, need to verify a function to know if the date needs to be shown in US/Non-US date format (dd/MM/YYYY vs mm/DD/YYYY).
To achieve this, I have coded below snippets, however is not yielding the required result. It is storing the value 10/11/2017 4:05, however, when presenting to US, i.e. getting value/ refreshing the page, its adding 5 more hours. Removed exceptions and other unnecessary code to make it simple:
public class DatetoString implements Serializable
{
private final DateFormat dateFormatter = createDateFormatter();
// Sets Date to model
public void setTypedValue(final Object val)
{
final String dateValue;
String dateTimeFormat = BooleanUtils.isFalse(getUSDateFormatConfig()) ? "dd/MM/yyyy HH:mm" : "MM/dd/yyyy HH:mm";
DateFormat df = new SimpleDateFormat(dateTimeFormat);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date singleDate = (Date) df.parse(val.toString());
dateValue = dateFormatter.format(singleDate);
model.setValue(dateValue.toString());
// Other code..
}
// Retrieves date from model
public Object getTypedValue()
{
final Object result;
String dateValue = model.iterator().next().getValue();
String dateTimeFormat = BooleanUtils.isFalse(getUSDateFormatConfig()) ? "dd/MM/yyyy HH:mm" : "MM/dd/yyyy HH:mm";
DateFormat df = new SimpleDateFormat(dateTimeFormat);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date singleDate = (Date) df.parse(dateValue);
result = dateFormatter.format(singleDate);
return result;
}
private DateFormat createDateFormatter()
{
final DateFormat result = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
result.setTimeZone(TimeZone.getTimeZone("GMT"));
return result;
}
}
java.time
You are using terrible old date-time classes that are troublesome, confusing, and poorly designed. They are now legacy, supplanted by the java.time classes. Avoid Date, Calendar, SimpleDateFormat, and such.
Use real time zones
By CST did you mean Central Standard Time or China Standard Time?
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/Chicago" );
Confirm time zone with user
If the time zone is critical for your work, you must confirm which zone was intended by their input. There are ways to guess at the zone or detect a default, but where important, make the zone part of your data-entry along with the date and the time-of-day. You can present a list from which they choose, or let them input a string name.
Ditto for Locale (discussed below). You can guess, but if critical, ask.
Parse and assemble
Save and retrieve the date in GMT timezone (date should be converted to String). So, if user saves date 10/10/2017 23:05, that will be saved as 10/11/2017 4:05 (5 hours ahead if saved in CST time for e.g.) in DB.
Parse the user input as a LocalDate and LocalTime using a DateTimeFormatter.
In real work you would add try-catch to capture DateTimeParseException thrown by faulty user input.
DateTimeFormatter fDate = DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ;
LocalDate ld = LocalDate.parse( inputDate , f ) ;
DateTimeFormatter fTime = DateTimeFormatter.ISO_LOCAL_TIME ;
LocalTime lt = LocalTime.parse( inputTime , f ) ;
Combine, and specify a time zone to get a ZonedDateTime object.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust to UTC by extracting an Instant which is always in UTC by definition. Same moment, same point on the timeline, but viewed through the lens of a different wall-clock.
Instant instant = zdt.toInstant() ;
Database
Persist to your database, in a column of type TIMESTAMP WITH TIME ZONE. The other type WITHOUT ignores any time zone or offset-from-UTC information and is most definitely not what you want to track actual moments in time.
myPreparedStatement.setObject( … , instant ) ;
Retrieve from database.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
While retrieving and presenting the date to UI, it should show as 10/10/2017 23:05 for CST users.
Adjust into whatever time zone the user expects/desires.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ; // Or "America/Chicago" or "America/Winnipeg" etc.
ZonedDateTime zdt = instant.atZone( z ) ;
Generate textual representation
Also, need to verify a function to know if the date needs to be shown in US/Non-US date format (dd/MM/YYYY vs mm/DD/YYYY).
Likewise, when generating text to represent that moment, automatically localize with whatever Locale the user expects/desires.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.FRANCE ; // Or Locale.US etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( l ) ;
String output = zdt.format( f ) ;
Note that Locale and time zone are orthogonal, unrelated and separate. You can have a French-speaking clerk in Morocco who is tracking a customer's delivery in India. So the moment is stored in UTC in the database running on a server in Canada, exchanged between database and other components in UTC, adjusted into India time zone to address the perspective of customer receiving delivery, and localized to French for reading by the user in Morocco.
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.
java.time
I agree wholeheartedly with Basil Bourque’s thorough and very knowledgeable answer. That your formats are old, has nothing to do with using the old and outdated date and time classes. Using the modern ones would lead to code that comes more naturally, and it would be easier to avoid problems like the one you are asking about. Also use time zone names in the format region/city, and beware that your JVM’s default time zone setting may be changed during runtime by other programs running in the same JVM.
EDIT: I didn’t want to spoil it by providing the code from the outset, but now you have solved your problem, for anyone reading along, here it is:
private static final DateTimeFormatter storeFormatter
= DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
private static final DateTimeFormatter usDisplayFormatter
= DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm");
private static final DateTimeFormatter internationalDisplayFormatter
= DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
private ZoneId userTimeZone = ZoneId.of("America/Rosario");
/** Sets Date to model */
public void setTypedValue(final Object val)
{
DateTimeFormatter parseFormatter = isUSDateFormatConfig()
? usDisplayFormatter : internationalDisplayFormatter;
final String dateValue = LocalDateTime.parse(val.toString(), parseFormatter)
.atZone(userTimeZone)
.withZoneSameInstant(ZoneOffset.UTC)
.format(storeFormatter);
model.setValue(dateValue);
// Other code..
}
/** Retrieves date from model */
public Object getTypedValue()
{
String dateValue = model.iterator().next().getValue();
DateTimeFormatter displayFormatter = isUSDateFormatConfig()
? usDisplayFormatter : internationalDisplayFormatter;
final Object result = LocalDateTime.parse(dateValue, storeFormatter)
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(userTimeZone)
.format(displayFormatter);
return result;
}
I called setTypedValue("10/29/2017 21:30"), and the date-time was stored as 10/30/2017 00:30:00. I was able to retrieve it as both 10/29/2017 21:30 in the US and 29/10/2017 21:30 outside.
For now I have hardcoded the user’s time zone as America/Rosario just to demonstrate the use of the region/city format. Instead of the userTimeZone variable you may of course use ZoneId.systemDefault(), but as I said, this may be changed under your feet by other programs running in the same JVM.
If you wanted to modernize your user interface, you could use DateTimeFormatter.ofLocalizedDateTime() instead of the hardcoded display formats, as also mentioned by Basil Bourque.
What was wrong in your code?
It seems to me that in your code in the question you are doing similar conversions in setTypedValue and getTypedValue. Shouldn’t you do opposite conversions? I would suppose that in getTypedValue you should use dateFormatter (the final instance variable) for parsing from GMT and then a formatter using local time zone (not GMT) for formatting.
Minor points:
You don’t need to cast the return value from df.parse() in any of the two places you are doing that, since it is already declared that that method returns a Date.
You don’t need to call toString() on dateValue since it is already declared a String, so the call will just return the same String again.

Printing Time and Date in both Universal Time and Standard Time

Writing a Java application that takes user input into a Time and Date class, but I am not sure how to take this user input and convert it into Universal and Standard time... I have spent multiple hours surfing the web and stack overflow and have not been able to find a solution.
I have hours, minutes, seconds, year, month, day all in separate integer variables and need to display them in Universal and Standard time.
Thanks for taking a look...
There are two solutions:
first is place all of input in the string and parse it:
String dateStr = ""
//put your input in this string in some format/ example:
//dateSttr = year + "." + month + "." + day + " " + hour + ":" + minute;
//It is better to use StringBuilder
DateFormat inputFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm");
//note that hh is 12h-format and HH is 24h-format
DateFormat outputFormat1 = new SimpleDateFormat("your_outputFormat");
DateFormat outputFormat2 = new SimpleDateFormat("your_another_outputFormat");
Date date = inputFormat.parse(dateStr);
String o1, o2;
o1 = outputFormat1.format(date);
o2 = outputFormat2.format(date);
//o1 and o2 is your result.
For the rules, how this formats is done, see javadoc
The second solution is to get a new date and set your parameters:
Calendar cln = Calendar.getInstance().clear();
//by default you get a calendar with current system time
//now set the fields. for example, day:
cln.set(Calendar.YEAR, 2015);
cln.set(Calendar.MONTH, Calendar.FEBRUARY);
cln.set(Calendar.DAY_OF_MONTH, 17);
cln.set(Calendar.HOUR_OF_DAY, 18);//Calendar.HOUR for 12h-format
cln.set(Calendar.MINUTE, 27);
See more about setting calendar in javadoc
Note, that in the second variant, you might have some fields undefiend.
If #JonSkeet 's assumption and mine is correct, you're starting with either UTC or your local time. Displaying it is just a matter of formatting your output.
For the other type of time, you add or subtract a number of hours, which you can find on the web. The tricky part is that this may push you into the next calendar day, or pull you back into the previous one. To deal with that, I figure you want to either
implement an adder for year, month, day, hour--or
convert those to decimal somethings (Excel uses days, for instance, where as I write this it's 42328.08813), shift the value by the appropriate number of hours, and convert it back.
java.time
The Answer by TEXHIK is correct, but outdated. Also, as others mentioned, I do not know what you mean by "Universal and Standard time". But I'll try to get you part way there.
As of Java 8, the old java.util.Date/.Calendar classes have been supplanted by the new java.time framework. 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.
The ZonedDateTime class has a factory method taking numbers for year, month, and so on.
Plus you must specify a time zone. If your numbers represent a date-time in UTC, use the ZoneOffset.UTC constant. For other time zones, specify a ZoneId object by using a proper time zone name; never use the 3-4 letter codes such as EST or IST as their are neither standardized nor unique.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
// ZoneId zoneId = ZoneOffset.UTC; // ZoneOffset is a subclass of ZoneId.
ZonedDateTime zdt = ZonedDateTime.of( 2015 , 1 , 2 , 3 , 4 , 5 , 6 , zoneId );
zdt: 2015-01-02T03:04:05.000000006-05:00[America/Montreal]
You can convert to UTC or another time zone.
ZonedDateTime zdt_Kolkata = zdt.withZoneSameInstant ( ZoneId.of("Asia/Kolkata") );
ZonedDateTime zdt_Utc = zdt.withZoneSameInstant ( ZoneOffset.UTC );
zdt_Kolkata: 2015-01-02T13:34:05.000000006+05:30[Asia/Kolkata]
zdt_Utc: 2015-01-02T08:04:05.000000006Z
If working with classes not yet updated for java.time, convert to a java.util.Date. First extract a Instant object, a moment on the timeline always in UTC.
java.util.Date date = java.util.Date.from ( zdt.toInstant () );

android get previous date of a corresponding date(not yesterday's date)

Please read question carefully before marking duplicate.
I want previous date of a corresponding date.(Not yesterday's date)
e.g. If user click button once he will be navigated to another screen and is shown data regarding yesterday.
And if he clicks again the same button on that screen, then data should be shown on day before yesterday....and so on... till data present in my database.
So I want to get previous date of a corresponding date. i.e. if I have date 31 Jan 2014(I'm using format 31012014 to store in db) then i should get date 30012014.
I know how to get yesterday's date e.g. below code
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
DateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.getDefault());
String yesterdayAsString = dateFormat.format(calendar.getTime());
which gives dates compared to today but I want previous date compared to some other valid date.
So how to get that.
You have to use SimpleDateFormat to convert String > Date, after Date > Calendar, for instance;
String sDate = "31012014";
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy", Locale.getDefault());
Date date = dateFormat.parse(sDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
String yesterdayAsString = dateFormat.format(calendar.getTime());
Use this, Its working and tested code.
private String getPreviousDate(String inputDate){
inputDate = "15-12-2015"; // for example
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
try {
Date date = format.parse(inputDate);
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.DATE, -1);
inputDate = format.format(c.getTime());
Log.d("asd", "selected date : "+inputDate);
System.out.println(date);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
inputDate ="";
}
return inputDate;
}
tl;dr
Use modern java.time classes. Repeatedly subtract a day to move backwards in time.
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.now( // Determine the current date as perceived in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Europe/Paris" ) // Use real time zone names in `Continent/Region` format, never 2-4 letter pseudo-zones such as PST, EST, IST, CEST, etc.
) // Returns a `LocalDate` object.
.minusDays( 1 ) // Move back in time by one day, for yesterday’s date. Returns another separate `LocalDate` object rather than modify the original, per Immutable Objects pattern.
.minusDays( 1 ) // Continue moving back in time another day.
.minus(
Period.ofDays( 1 ) // Define a span-of-time as any number of years-months-weeks-days.
) // Continuing to subtract yet another day.
.toString() // Generate text representing that last generated `LocalDate` date-value using standard ISO 8601 format.
When parsing your text inputs.
LocalDate
.parse(
"30012014" ,
DateTimeFormatter.ofPattern( "ddMMuuuu" )
)
.minusDay( 1 )
.minus(
Period.ofDays( 1 )
)
java.time
The modern approach uses the java.time classes that years ago supplanted the troublesome old date-time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
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.
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 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 ) ;
Date math
Your Question is not clear, but it seems you simply want to increment backwards in time one day at a time. This is quite easy with the LocalDate class offering plus & minus methods.
Call the convenience method, LocalDate::minusDays.
LocalDate yesterday = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ).minusDays( 1 ) ;
To move backwards, subtract again.
LocalDate localDatePrior = yesterday.minusDays( 1 ) ;
And continue onwards.
localDatePrior = localDatePrior.minusDays( 1 ) ;
You can soft-code the period of time to subtract using the Period class with the LocalDate.minus method.
Period p = Period.ofDays( 1 ) ;
LocalDate localDatePrior = yesterday.minus( p ) ;
Database
(I'm using format 31012014 to store in db)
Don’t.
To store a date-only value in your database, use a date-only type in your column. In a SQL-compliant database, the type will be DATE for a date-only value.
As of JDBC 4.2 we can directly exchange java.time objects with the database.
myPreparedStatement.setObject( … , localDate ) ;
Retrieval.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ;
Parsing
But to directly address your current situation, you can parse your string with its peculiar format of DDMMYYYY.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "ddMMuuuu" ) ;
LocalDate localDate = LocalDate.parse( "30012014" , f ) ;
String output = localDate.toString() ; // Generate text in standard ISO 8601 format.
By the way, rather than invent your own date-time format, always use standard ISO 8601 formats when exchanging date-time values as text. The java.time classes wisely use these formats by default when parsing/generating strings.
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….
Try this one
String prevDate;
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String todayDate=df.format(c);
Date date = null;
try {
date = df.parse(todayDate);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
prevDate = df.format(calendar.getTime());
Test=(TextView)findViewById(R.id.test);
Test.setText(prevDate);
You've got everything right, except before you "add" -1 days, you need to set it to the date you want (before finding the previous date previous):
Calendar calendar = Calendar.getInstance();
calendar.set(2014, Calendar.JUNE, 9);
calendar.add(Calendar.DATE, -1);
...
First off just as a tip, it is better to store your dates as timestamps like so you won't be dependent on time formats.
As for your question, just keep your current date in a variable and send it to your method once the button is clicked and then subtract an extra day
Calendar curDate = Calendar.getInstance();
curDate.add(Calendar.DATE, -1);
and use your curDate variable from then on
Try this:
final Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -1);
String yesterdayAsString = fmtOut.format(calendar.getTime());
long calendar=Calendar.getInstance().getTimeInMillis()-1000*60*60*24;
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
String date = sdf.format(calendar);

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