In other words, I want functionality that provides Joda-Time:
today = today.withTime(0, 0, 0, 0);
but without Joda-Time, only with java.util.Date.
Methods such as .setHours() an开发者_开发技巧d etc. are deprecated. Is there are more correct way?
Date today = new Date();
today.setHours(0); //same for minutes and seconds
Since the methods are deprecated, you can do this with Calendar
:
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0); // same for minutes and seconds
And if you need a Date
object in the end, simply call today.getTime()
Is there are more correct way?
Yes, there is.
LocalDate.now(
ZoneId.of( "America/Montreal" )
).atStartOfDay(
ZoneId.of( "America/Montreal" )
)
java.time
Java 8 and later now has the new java.time framework built-in. See Tutorial. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
Examples
Some examples follow, using java.time. Note how they specify a time zone. If omitted, your JVM’s current default time zone. That default can vary, even changing at any moment during runtime, so I suggest you specify a time zone explicitly rather than rely implicitly on the default.
Here is an example of date-only, without time-of-day nor time zone.
ZoneId zonedId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zonedId );
System.out.println( "today : " + today );
today : 2015-10-19
Here is an example of getting current date-time.
ZoneId zonedId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zonedId );
System.out.println( "zdt : " + zdt );
When run:
zdt : 2015-10-19T18:07:02.910-04:00[America/Montreal]
First Moment Of The Day
The Question asks for the date-time where the time is set to zero. This assumes the first moment of the day is always the time 00:00:00.0
but that is not always the case. Daylight Saving Time (DST) and perhaps other anomalies mean the day may begin at a different time such as 01:00.0
.
Fortunately, java.time has a facility to determine the first moment of a day appropriate to a particular time zone, LocalDate::atStartOfDay
. Let's see some code using the LocalDate
named today
and the ZoneId
named zoneId
from code above.
ZonedDateTime todayStart = today.atStartOfDay( zoneId );
zdt : 2015-10-19T00:00:00-04:00[America/Montreal]
Interoperability
If you must have a java.util.Date for use with classes not yet updated to work with the java.time types, convert. Call the java.util.Date.from( Instant instant )
method.
java.util.Date date = java.util.Date.from( zdt.toInstant() );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
DateUtils from Apache Commons-Lang. Watch out for time zone!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
found here
If you want midnight (0:00am) for the current date, you can just use the default constructor and zero out the time portions:
Date today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0);
edit: update with Calendar
since those methods are deprecated
Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();
Use this code ;
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
This will shown as :
Feb 5, 2013 12:39:02PM
Use this code to easy get Date & Time :
package date.time;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTime {
public static void main(String[] args) {
SimpleDateFormat dnt = new SimpleDateFormat("dd/MM/yy :: HH:mm:ss");
Date date = new Date();
System.out.println("Today Date & Time at Now :"+dnt.format(date));
}
}
Code To Get Today's date in any specific Format
You can define the desired format in SimpleDateFormat instance to get the date in that specific formate
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String todaysdate = dateFormat.format(date);
System.out.println("Today's date : " + todaysdate);
Follow below links to see the valid date format combination.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
CODE : To get x days ahead or Previous from Today's date, To get the past date or Future date.
For Example :
Today date : 11/27/2018
xdayFromTodaysDate = 2 to get date as 11/29/2018
xdayFromTodaysDate = -2 to get date as 11/25/2018
public String getAniversaryDate(int xdayFromTodaysDate ){
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("Today's date : " + todaysdate);
return aniversaryDate;
}
CODE : To get x days ahead or Previous from a Given date
public String getAniversaryDate(String givendate, int xdayFromTodaysDate ){
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = dateFormat.parse(givendate);
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("aniversaryDate : " + aniversaryDate);
return aniversaryDate;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
精彩评论