This is my Below function in which I am passing timestamp, I need only the date in return from the timestamp not the Hours and Second. With the below code I am getting-
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000);
return DateFormat.getInstance().format(date).toString();
}
This is the output I am getting.
11/4/01 11:27 PM
But I need only the date like this
2001-11-04
Any suggestions?
Use SimpleDateFormat instead:
private String toDate(long timestamp) {
Date date = new Date(timestamp * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
Updated: Java 8 solution:
private String toDate(long timestamp) {
LocalDate date = Instant.ofEpochMilli(timestamp * 1000).atZone(ZoneId.systemDefault()).toLocalDate();
return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
}
You can use this code to get the required results
protected Timestamp timestamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
protected String today_Date=timestamp.toString().split(" ")[0];
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
You can use Instant#ofEpochSecond to get an Instant out of the given timestamp and then use LocalDate.ofInstant to get a LocalDate out of the obtained Instant.
Demo:
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(toDate(1636120105L));
}
static LocalDate toDate(long timestamp) {
return LocalDate.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
}
}
Output:
2021-11-05
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time. Check this answer and this answer to learn how to use java.time API with JDBC.
* If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.
Joda-Time
The Joda-Time library offers a LocalDate class to represent a date-only value without any time-of-day nor time zone.
Time Zone
Determining a date requires a time zone. A moment just after midnight in Paris means a date that is a day ahead of the same simultaneous moment in Montréal. If you neglect to specify a time zone, the JVM’s current default time zone is applied – probably not what you want as results may vary.
Example Code
long millisecondsSinceUnixEpoch = ( yourNumberOfSecondsSinceUnixEpoch * 1000 ); // Convert seconds to milliseconds.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
LocalDate localDate = new LocalDate( millisecondsSinceUnixEpoch, timeZone );
String output = localDate.toString(); // Defaults to ISO 8601 standard format, YYYY-MM-DD.
Previous Day
To get the day before, as requested in a comment.
LocalDate dayBefore = localDate.minusDays( 1 );
Convert to j.u.Date
The java.util.Date & .Calendar classes should be avoided as they are notoriously troublesome. But if required, you may convert.
java.util.Date date = localDate.toDate(); // Time-of-day set to earliest valid for that date.
Related
I am trying to pass values to a function as start date and end date. As of now i hard code these values where the start date would be 20210401 and end date would be 20210419. 01 is the date, 04 is the month and 2021 is the year.
I want to pass these during run time where start date would be start date of that current month, end date should be 2 days before the current date of the current month. For example if the current month is october and todays date is 15th October, 2021. Then the start date should be 20211001 and end date should be 20211013. Please suggest any code in java. It would be really helpful.
Here is a solution using LocalDate to calculate the expected dates. Note that if the current date is on the 1st or 2nd of the month the code will use current date as end date rather than doing any calculation. Feel free to change this as you see fit.
LocalDate now = LocalDate.now();
LocalDate first = now.withDayOfMonth(1);
LocalDate limit = now.withDayOfMonth(3);
LocalDate last = null;
if (now.isBefore(limit)) {
last = now;
} else {
last = now.minusDays(2);
}
I want to pass these during run time where start date would be start
date of that current month, end date should be 2 days before the
current date of the current month.
I suggest you do it using the modern date-time API as demonstrated below:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
LocalDate startDate = today.with(TemporalAdjusters.firstDayOfMonth());
LocalDate endDate = today.minusDays(2);
// Use the following optional block if your requirement is to reset the end date
// to the start date in case it falls before the start date e.g. when the
// current date is on the 1st or the 2nd day of the month
//////////////////////// Start of optional block/////////////////////
if (endDate.isBefore(startDate)) {
endDate = startDate;
}
///////////////////////// End of optional block//////////////////////
// Get the strings representing the dates in the desired format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMMdd", Locale.ENGLISH);
String strStartDate = startDate.format(dtf);
String strEndDate = endDate.format(dtf);
System.out.println(strStartDate);
System.out.println(strEndDate);
}
}
Output:
20210401
20210419
Note: If your application is supposed to be used in a different timezone than that of your application's JVM, replace LocalDate with ZonedDateTime and intitialize today with ZonedDateTime.now(ZoneId zone) passing the applicable timezone e.g. ZoneId.of("Asia/Kolkata").
Learn more about the modern date-time API from Trail: Date Time.
How about using the legacy date-time API?
The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API* .
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Here's a code snippet which may help. Here I am taking the local system time as the endDate and going back TWO days prior to get your startDate.
// the format you'd like to display your date as.
String pattern ="yyyyMMdd";
// this formats the date to look how you'd want it to look
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
//Get date for 2 day prior to currentDate.
long SINGLE_DAY_IN_MS = 1000 * 60 * 60 *24;
long nDaysToGoBack = 2;
//create 'startDate' variable from milliseconds as an input
Date startDate = new Date(System.currentTimeMillis()- (nDaysToGoBack*SINGLE_DAY_IN_MS));
// Set 'endDate' as your current date.
Date endDate = new Date(System.currentTimeMillis());
System.out.println();
System.out.println("Start Date: "+ simpleDateFormat.format(startDate));
System.out.println("End Date: "+ simpleDateFormat.format(endDate));
I am sure whether you want to use your current system date or whether you want to manually pass a different date into your function.
If you want to manually pass in a date (for example, 10 Jan 2021) into your function during runtime you can use the statement:
Date endDate = simpleDateFormat.parse("20210110");
and then find a way to subtract the 2 days from that endDate variable to get your startDate variable.
I am trying to use a java.util.Date as input and then creating a query with it - so I need a java.sql.Date.
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.
Nevermind....
public class MainClass {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
}
}
explains it. The link is http://www.java2s.com/Tutorial/Java/0040__Data-Type/ConvertfromajavautilDateObjecttoajavasqlDateObject.htm
tl;dr
How to convert java.util.Date to java.sql.Date?
Don’t.
Both Date classes are outmoded. Sun, Oracle, and the JCP community gave up on those legacy date-time classes years ago with the unanimous adoption of JSR 310 defining the java.time classes.
Use java.time classes instead of legacy java.util.Date & java.sql.Date with JDBC 4.2 or later.
Convert to/from java.time if inter-operating with code not yet updated to java.time.
Legacy
Modern
Conversion
java.util.Date
java.time.Instant
java.util.Date.toInstant()java.util.Date.from( Instant )
java.sql.Date
java.time.LocalDate
java.sql.Date.toLocalDate()java.sql.Date.valueOf( LocalDate )
Example query with PreparedStatement.
myPreparedStatement.setObject(
… , // Specify the ordinal number of which argument in SQL statement.
myJavaUtilDate.toInstant() // Convert from legacy class `java.util.Date` (a moment in UTC) to a modern `java.time.Instant` (a moment in UTC).
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to a particular time zone, to determine a date. Instantiating a `ZonedDateTime`.
.toLocalDate() // Extract a date-only `java.time.LocalDate` object from the date-time `ZonedDateTime` object.
)
Replacements:
Instant instead of java.util.DateBoth represent a moment in UTC. but now with nanoseconds instead of milliseconds.
LocalDate instead of java.sql.DateBoth represent a date-only value without a time of day and without a time zone.
Details
If you are trying to work with date-only values (no time-of-day, no time zone), use the LocalDate class rather than java.util.Date.
java.time
In Java 8 and later, the troublesome old date-time classes bundled with early versions of Java have been supplanted by the new java.time package. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
A SQL data type DATE is meant to be date-only, with no time-of-day and no time zone. Java never had precisely such a class† until java.time.LocalDate in Java 8. Let's create such a value by getting today's date according to a particular time zone (time zone is important in determining a date as a new day dawns earlier in Paris than in Montréal, for example).
LocalDate todayLocalDate = LocalDate.now( ZoneId.of( "America/Montreal" ) ); // Use proper "continent/region" time zone names; never use 3-4 letter codes like "EST" or "IST".
At this point, we may be done. If your JDBC driver complies with JDBC 4.2 spec, you should be able to pass a LocalDate via setObject on a PreparedStatement to store into a SQL DATE field.
myPreparedStatement.setObject( 1 , localDate );
Likewise, use ResultSet::getObject to fetch from a SQL DATE column to a Java LocalDate object. Specifying the class in the second argument makes your code type-safe.
LocalDate localDate = ResultSet.getObject( 1 , LocalDate.class );
In other words, this entire Question is irrelevant under JDBC 4.2 or later.
If your JDBC driver does not perform in this manner, you need to fall back to converting to the java.sql types.
Convert to java.sql.Date
To convert, use new methods added to the old date-time classes. We can call java.sql.Date.valueOf(…) to convert a LocalDate.
java.sql.Date sqlDate = java.sql.Date.valueOf( todayLocalDate );
And going the other direction.
LocalDate localDate = sqlDate.toLocalDate();
Converting from java.util.Date
While you should avoid using the old date-time classes, you may be forced to when working with existing code. If so, you can convert to/from java.time.
Go through the Instant class, which represents a moment on the timeline in UTC. An Instant is similar in idea to a java.util.Date. But note that Instant has a resolution up to nanoseconds while java.util.Date has only milliseconds resolution.
To convert, use new methods added to the old classes. For example, java.util.Date.from( Instant ) and java.util.Date::toInstant.
Instant instant = myUtilDate.toInstant();
To determine a date, we need the context of a time zone. For any given moment, the date varies around the globe by time zone. Apply a ZoneId to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
LocalDate localDate = zdt.toLocalDate();
† The java.sql.Date class pretends to be date-only without a time-of-day but actually does a time-of-day, adjusted to a midnight time. Confusing? Yes, the old date-time classes are a mess.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. 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.
With the other answer you may have troubles with the time info (compare the dates with unexpected results!)
I suggest:
java.util.Calendar cal = Calendar.getInstance();
java.util.Date utilDate = new java.util.Date(); // your util date
cal.setTime(utilDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime()); // your sql date
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
This function will return a converted SQL date from java date object.
public java.sql.Date convertJavaDateToSqlDate(java.util.Date date) {
return new java.sql.Date(date.getTime());
}
Converting java.util.Date to java.sql.Date will lose hours, minutes and seconds. So if it is possible, I suggest you to use java.sql.Timestamp like this:
prepareStatement.setTimestamp(1, new Timestamp(utilDate.getTime()));
For more info, you can check this question.
In my case of picking date from JXDatePicker (java calender) and getting it stored in database as SQL Date type, below works fine ..
java.sql.Date date = new java.sql.Date(pickedDate.getDate().getTime());
where pickedDate is object of JXDatePicker
This function will return a converted SQL date from java date object.
public static java.sql.Date convertFromJAVADateToSQLDate(
java.util.Date javaDate) {
java.sql.Date sqlDate = null;
if (javaDate != null) {
sqlDate = new Date(javaDate.getTime());
}
return sqlDate;
}
Format your java.util.Date first. Then use the formatted date to get the date in java.sql.Date
java.util.Date utilDate = "Your date"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final String stringDate= dateFormat.format(utilDate);
final java.sql.Date sqlDate= java.sql.Date.valueOf(stringDate);
Here the example of converting Util Date to Sql date and ya this is one example what i am using in my project might be helpful to you too.
java.util.Date utilStartDate = table_Login.getDob();(orwhat ever date your give form obj)
java.sql.Date sqlStartDate = new java.sql.Date(utilStartDate.getTime());(converting date)
I am a novice: after much running around this worked. Thought might be useful
String bufDt = bDOB.getText(); //data from form
DateFormat dF = new SimpleDateFormat("dd-MM-yyyy"); //data in form is in this format
Date bbdt = (Date)dF.parse(bufDt); // string data is converted into java util date
DateFormat dsF = new SimpleDateFormat("yyyy-MM-dd"); //converted date is reformatted for conversion to sql.date
String ndt = dsF.format(bbdt); // java util date is converted to compatible java sql date
java.sql.Date sqlDate= java.sql.Date.valueOf(ndt); // finally data from the form is convered to java sql. date for placing in database
Method for comparing 2 dates (util.date or sql.date)
public static boolean isSameDay(Date a, Date b) {
Calendar calA = new GregorianCalendar();
calA.setTime(a);
Calendar calB = new GregorianCalendar();
calB.setTime(b);
final int yearA = calA.get(Calendar.YEAR);
final int monthA = calA.get(Calendar.MONTH);
final int dayA = calA.get(Calendar.DAY_OF_YEAR);
final int yearB = calB.get(Calendar.YEAR);
final int monthB = calB.get(Calendar.MONTH);
final int dayB = calB.get(Calendar.DAY_OF_YEAR);
return yearA == yearB && monthA == monthB && dayA == dayB;
}
try with this
public static String toMysqlDateStr(Date date) {
String dateForMySql = "";
if (date == null) {
dateForMySql = null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateForMySql = sdf.format(date);
}
return dateForMySql;
}
I think the best way to convert is:
static java.sql.Timestamp SQLDateTime(Long utilDate) {
return new java.sql.Timestamp(utilDate);
}
Date date = new Date();
java.sql.Timestamp dt = SQLDateTime(date.getTime());
If you want to insert the dt variable into an SQL table you can do:
insert into table (expireAt) values ('"+dt+"');
i am using the following code please try it out
DateFormat fm= new SimpleDateFormatter();
specify the format of the date you want
for example "DD-MM_YYYY" or 'YYYY-mm-dd' then use the java Date datatype as
fm.format("object of java.util.date");
then it will parse your date
You can use this method to convert util date to sql date,
DateUtilities.convertUtilDateToSql(java.util.Date)
I was trying the following coding that worked fine.
java.util.Date utilDate = new java.util.Date(); java.sql.Date
sqlDate = new java.sql.Date(utilDate);
If you are usgin Mysql a date column can be passed a String representation of this date
so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement
here is the code illustration:
private String converUtilDateToSqlDate(java.util.Date utilDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sqlDate = sdf.format(utilDate);
return sqlDate;
}
String date = converUtilDateToSqlDate(otherTransaction.getTransDate());
//then pass this date in you sql statement
I'm trying to convert some string that is in UTC time to a java Calendar object that should be set to GMT-5.
My current UTC string input is this:
UTC date : 20050329174411
I use this code (I detect the 'pattern' as shown below):
DateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = dateFormat.parse(utcDate);
calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-5"));
calendar.setTime(date);
I then printed the time like this:
calendar.getTime()
And I got this result:
GMT date : Tue Mar 29 17:44:11 EST 2005
I need to support theses date/time string patterns:
FORMAT_UTC4 = "yyyy";
FORMAT_UTC6 = "yyyyMM";
FORMAT_UTC8 = "yyyyMMdd";
FORMAT_UTC10 = "yyyyMMddHH";
FORMAT_UTC12 = "yyyyMMddHHmm";
FORMAT_UTC14 = "yyyyMMddHHmmss";
I would be expecting the time to be set to "12:44:11". I have read a couple of examples and I find date time handling pretty confusing. For me, it's always the same, I get some sort of string formatted UTC and I convert it to GMT-5. I really feel it should be easy!
Ref 1 : How can I get the current date and time in UTC or GMT in Java?
Ref 2 : How to handle calendar TimeZones using Java?
You must set the SimpleDateFormat's time zone to UTC before parsing the date. Else, it uses your default timezone.
And to display the date in the "GMT-5" timezone, you should use another DateFormat, with the timezone set to GMT-5, and format the date with this DateFormat. The toString() method of Date uses your default time zone to transform the date into something readable.
java.time
Note that GMT-5 or timezone offset of -05:00 hours is a fixed offset i.e. independent of the DST and type to represent a date-time with timezone offset is OffsetDateTime.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochMilli(20050329174411L);
OffsetDateTime odt = instant.atOffset(ZoneOffset.of("-05:00"));
// Alternatively
// OffsetDateTime.ofInstant(instant, ZoneOffset.of("-05:00"));
System.out.println(odt);
}
}
Output:
2605-05-15T18:52:54.411-05:00
If you are looking for an automatic adjustment of timezone offset as per the DST, use ZonedDateTime.
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochMilli(20050329174411L);
ZonedDateTime zdt = instant.atZone(ZoneId.of("America/Chicago"));
// Alternatively
// ZonedDateTime.ofInstant(instant, ZoneId.of("America/Chicago"));
System.out.println(zdt);
}
}
Output:
2605-05-15T18:52:54.411-05:00[America/Chicago]
Learn more about java.time, the modern date-time API* from Trail: Date Time.
If at all you need an object of java.util.Calendar from this object of ZonedDateTime, you can do so as follows:
Calendar calendar = Calendar.getInstance();
calendar.setTime(Date.from(zdt.toInstant()));
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
I want to get the UTC time for 01/01/2100 in Java to '2100-01-01 00:00:00'. I am getting "2100-01-01 00:08:00". Any idea, how to correct this.
public Date getFinalTime() {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date finalTime = null;
try
{
finalTime = df.parse("01/01/2100");
} catch (ParseException e)
{
e.printStackTrace();
}
calendar.setTime(finalTime);
return calendar.getTime();
}
You need to specify the time zone for the SimpleDateFormat as well - currently that's parsing midnight local time which is ending up as 8am UTC.
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setTimeZone(utc);
Date finalTime = null;
try
{
finalTime = df.parse("01/01/2100");
} catch (ParseException e)
{
e.printStackTrace();
}
calendar.setTime(finalTime);
As ever though, I would personally recommend using Joda Time which is far more capable in general. I'd be happy to translate your example into Joda Time if you want.
Additionally, I see you're returning calendar.getTime() - that's just the same as returning finalTime as soon as you've computed it.
Finally, just catching a ParseException and carrying on as if it didn't happen is a very bad idea. I'm hoping this is just sample code and it doesn't reflect your real method. Likewise I'm assuming that really you'll be parsing some other text - if you're not, then as Eyal said, you should just call methods on Calendar directly. (Or, again, use Joda Time.)
You need to set the time zone of the SimpleDateFormat object as well, otherwise it assumes the default time zone.
Anyway, it seems like using only a Calendar is enough in your case. Use its setters to set the right values for all fields (year, month, day, hour, etc), and then retrieve the time.
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice at the Home Page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern API:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDate = "01/01/2100";
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("d/M/u", Locale.ENGLISH);
ZonedDateTime zdt = LocalDate.parse(strDate, dtfInput)
.atStartOfDay(ZoneId.of("Etc/UTC"));
// Default format
System.out.println(zdt);
// Getting and displaying LocalDateTime
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// A custom format
DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
// Alternatively dtfOutput.format(ldt);
String formatted = dtfOutput.format(zdt);
System.out.println(formatted);
// Converting to some other types
OffsetDateTime odt = zdt.toOffsetDateTime();
Instant instant = zdt.toInstant();
System.out.println(odt);
System.out.println(instant);
}
}
Output:
2100-01-01T00:00Z[Etc/UTC]
2100-01-01T00:00
2100-01-01 00:00:00
2100-01-01T00:00Z
2100-01-01T00:00:00Z
ONLINE DEMO
The Z in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
Note: The Date-Time without timezone name or timezone offset should be represented by LocalDateTime (which is used for events that are normally not represented with timezone information). In this sense, LocalDateTime is useless in this case and you should use ZonedDateTime itself or Instant or OffsetDateTime. I recommend you also check this answer and this answer if you are dealing with JDBC.
Learn more about java.time, the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
java.time
Like Arvind Kumar Avinash I very clearly recommend that you use java.time, the modern Java date and time API, for your date and time work. If what you want is a fixed (constant) date and time, use OffsetDateTime.of().
OffsetDateTime finalTime = OffsetDateTime.of(2100, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC);
System.out.println(finalTime);
Output:
2100-01-01T00:00Z
The trailing Z means UTC.
Tutorial link
Oracle tutorial: Date Time explaining how to use java.time.
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(utc);
DateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");
dateformat.setTimeZone(utc);
Timezone needs to be set.
I am trying to use a java.util.Date as input and then creating a query with it - so I need a java.sql.Date.
I was surprised to find that it couldn't do the conversion implicitly or explicitly - but I don't even know how I would do this, as the Java API is still fairly new to me.
Nevermind....
public class MainClass {
public static void main(String[] args) {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
}
}
explains it. The link is http://www.java2s.com/Tutorial/Java/0040__Data-Type/ConvertfromajavautilDateObjecttoajavasqlDateObject.htm
tl;dr
How to convert java.util.Date to java.sql.Date?
Don’t.
Both Date classes are outmoded. Sun, Oracle, and the JCP community gave up on those legacy date-time classes years ago with the unanimous adoption of JSR 310 defining the java.time classes.
Use java.time classes instead of legacy java.util.Date & java.sql.Date with JDBC 4.2 or later.
Convert to/from java.time if inter-operating with code not yet updated to java.time.
Legacy
Modern
Conversion
java.util.Date
java.time.Instant
java.util.Date.toInstant()java.util.Date.from( Instant )
java.sql.Date
java.time.LocalDate
java.sql.Date.toLocalDate()java.sql.Date.valueOf( LocalDate )
Example query with PreparedStatement.
myPreparedStatement.setObject(
… , // Specify the ordinal number of which argument in SQL statement.
myJavaUtilDate.toInstant() // Convert from legacy class `java.util.Date` (a moment in UTC) to a modern `java.time.Instant` (a moment in UTC).
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to a particular time zone, to determine a date. Instantiating a `ZonedDateTime`.
.toLocalDate() // Extract a date-only `java.time.LocalDate` object from the date-time `ZonedDateTime` object.
)
Replacements:
Instant instead of java.util.DateBoth represent a moment in UTC. but now with nanoseconds instead of milliseconds.
LocalDate instead of java.sql.DateBoth represent a date-only value without a time of day and without a time zone.
Details
If you are trying to work with date-only values (no time-of-day, no time zone), use the LocalDate class rather than java.util.Date.
java.time
In Java 8 and later, the troublesome old date-time classes bundled with early versions of Java have been supplanted by the new java.time package. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
A SQL data type DATE is meant to be date-only, with no time-of-day and no time zone. Java never had precisely such a class† until java.time.LocalDate in Java 8. Let's create such a value by getting today's date according to a particular time zone (time zone is important in determining a date as a new day dawns earlier in Paris than in Montréal, for example).
LocalDate todayLocalDate = LocalDate.now( ZoneId.of( "America/Montreal" ) ); // Use proper "continent/region" time zone names; never use 3-4 letter codes like "EST" or "IST".
At this point, we may be done. If your JDBC driver complies with JDBC 4.2 spec, you should be able to pass a LocalDate via setObject on a PreparedStatement to store into a SQL DATE field.
myPreparedStatement.setObject( 1 , localDate );
Likewise, use ResultSet::getObject to fetch from a SQL DATE column to a Java LocalDate object. Specifying the class in the second argument makes your code type-safe.
LocalDate localDate = ResultSet.getObject( 1 , LocalDate.class );
In other words, this entire Question is irrelevant under JDBC 4.2 or later.
If your JDBC driver does not perform in this manner, you need to fall back to converting to the java.sql types.
Convert to java.sql.Date
To convert, use new methods added to the old date-time classes. We can call java.sql.Date.valueOf(…) to convert a LocalDate.
java.sql.Date sqlDate = java.sql.Date.valueOf( todayLocalDate );
And going the other direction.
LocalDate localDate = sqlDate.toLocalDate();
Converting from java.util.Date
While you should avoid using the old date-time classes, you may be forced to when working with existing code. If so, you can convert to/from java.time.
Go through the Instant class, which represents a moment on the timeline in UTC. An Instant is similar in idea to a java.util.Date. But note that Instant has a resolution up to nanoseconds while java.util.Date has only milliseconds resolution.
To convert, use new methods added to the old classes. For example, java.util.Date.from( Instant ) and java.util.Date::toInstant.
Instant instant = myUtilDate.toInstant();
To determine a date, we need the context of a time zone. For any given moment, the date varies around the globe by time zone. Apply a ZoneId to get a ZonedDateTime.
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant ( instant , zoneId );
LocalDate localDate = zdt.toLocalDate();
† The java.sql.Date class pretends to be date-only without a time-of-day but actually does a time-of-day, adjusted to a midnight time. Confusing? Yes, the old date-time classes are a mess.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. 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.
With the other answer you may have troubles with the time info (compare the dates with unexpected results!)
I suggest:
java.util.Calendar cal = Calendar.getInstance();
java.util.Date utilDate = new java.util.Date(); // your util date
cal.setTime(utilDate);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime()); // your sql date
System.out.println("utilDate:" + utilDate);
System.out.println("sqlDate:" + sqlDate);
This function will return a converted SQL date from java date object.
public java.sql.Date convertJavaDateToSqlDate(java.util.Date date) {
return new java.sql.Date(date.getTime());
}
Converting java.util.Date to java.sql.Date will lose hours, minutes and seconds. So if it is possible, I suggest you to use java.sql.Timestamp like this:
prepareStatement.setTimestamp(1, new Timestamp(utilDate.getTime()));
For more info, you can check this question.
In my case of picking date from JXDatePicker (java calender) and getting it stored in database as SQL Date type, below works fine ..
java.sql.Date date = new java.sql.Date(pickedDate.getDate().getTime());
where pickedDate is object of JXDatePicker
This function will return a converted SQL date from java date object.
public static java.sql.Date convertFromJAVADateToSQLDate(
java.util.Date javaDate) {
java.sql.Date sqlDate = null;
if (javaDate != null) {
sqlDate = new Date(javaDate.getTime());
}
return sqlDate;
}
Format your java.util.Date first. Then use the formatted date to get the date in java.sql.Date
java.util.Date utilDate = "Your date"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
final String stringDate= dateFormat.format(utilDate);
final java.sql.Date sqlDate= java.sql.Date.valueOf(stringDate);
Here the example of converting Util Date to Sql date and ya this is one example what i am using in my project might be helpful to you too.
java.util.Date utilStartDate = table_Login.getDob();(orwhat ever date your give form obj)
java.sql.Date sqlStartDate = new java.sql.Date(utilStartDate.getTime());(converting date)
I am a novice: after much running around this worked. Thought might be useful
String bufDt = bDOB.getText(); //data from form
DateFormat dF = new SimpleDateFormat("dd-MM-yyyy"); //data in form is in this format
Date bbdt = (Date)dF.parse(bufDt); // string data is converted into java util date
DateFormat dsF = new SimpleDateFormat("yyyy-MM-dd"); //converted date is reformatted for conversion to sql.date
String ndt = dsF.format(bbdt); // java util date is converted to compatible java sql date
java.sql.Date sqlDate= java.sql.Date.valueOf(ndt); // finally data from the form is convered to java sql. date for placing in database
Method for comparing 2 dates (util.date or sql.date)
public static boolean isSameDay(Date a, Date b) {
Calendar calA = new GregorianCalendar();
calA.setTime(a);
Calendar calB = new GregorianCalendar();
calB.setTime(b);
final int yearA = calA.get(Calendar.YEAR);
final int monthA = calA.get(Calendar.MONTH);
final int dayA = calA.get(Calendar.DAY_OF_YEAR);
final int yearB = calB.get(Calendar.YEAR);
final int monthB = calB.get(Calendar.MONTH);
final int dayB = calB.get(Calendar.DAY_OF_YEAR);
return yearA == yearB && monthA == monthB && dayA == dayB;
}
try with this
public static String toMysqlDateStr(Date date) {
String dateForMySql = "";
if (date == null) {
dateForMySql = null;
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateForMySql = sdf.format(date);
}
return dateForMySql;
}
I think the best way to convert is:
static java.sql.Timestamp SQLDateTime(Long utilDate) {
return new java.sql.Timestamp(utilDate);
}
Date date = new Date();
java.sql.Timestamp dt = SQLDateTime(date.getTime());
If you want to insert the dt variable into an SQL table you can do:
insert into table (expireAt) values ('"+dt+"');
i am using the following code please try it out
DateFormat fm= new SimpleDateFormatter();
specify the format of the date you want
for example "DD-MM_YYYY" or 'YYYY-mm-dd' then use the java Date datatype as
fm.format("object of java.util.date");
then it will parse your date
You can use this method to convert util date to sql date,
DateUtilities.convertUtilDateToSql(java.util.Date)
I was trying the following coding that worked fine.
java.util.Date utilDate = new java.util.Date(); java.sql.Date
sqlDate = new java.sql.Date(utilDate);
If you are usgin Mysql a date column can be passed a String representation of this date
so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement
here is the code illustration:
private String converUtilDateToSqlDate(java.util.Date utilDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sqlDate = sdf.format(utilDate);
return sqlDate;
}
String date = converUtilDateToSqlDate(otherTransaction.getTransDate());
//then pass this date in you sql statement