I have a problem resetting hours in Java. For a given date I want to set the hours to 00:00:00.
This is my code :
/**
* Resets milliseconds, seconds, minutes and hours from the provided date
*
* #param date
* #return
*/
public static Date trim(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
return calendar.getTime();
}
The problem is that sometimes the time is 12:00:00 and sometimes it is 00:00:00 and when I query the database for an entity that was saved on 07.02.2013 00:00:00 and the actual entity time, that is stored, is 12:00:00 the query fails.
I know that 12:00:00 == 00:00:00!
I am using AppEngine. Is this an appengine bug, problem or some other issue? Or does it depend on something else?
Use another constant instead of Calendar.HOUR, use Calendar.HOUR_OF_DAY.
calendar.set(Calendar.HOUR_OF_DAY, 0);
Calendar.HOUR uses 0-11 (for use with AM/PM), and Calendar.HOUR_OF_DAY uses 0-23.
To quote the Javadocs:
public static final int HOUR
Field number for get and set indicating
the hour of the morning or afternoon. HOUR is used for the 12-hour
clock (0 - 11). Noon and midnight are represented by 0, not by 12.
E.g., at 10:04:15.250 PM the HOUR is 10.
and
public static final int HOUR_OF_DAY
Field number for get and set
indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour
clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
Testing ("now" is currently c. 14:55 on July 23, 2013 Pacific Daylight Time):
public class Main
{
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
System.out.println(sdf.format(now.getTime()));
now.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(now.getTime()));
}
}
Output:
$ javac Main.java
$ java Main
2013-07-23 12:00:00
2013-07-23 00:00:00
java.time
Using the java.time framework built into Java 8 and later. See Tutorial.
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now(); # 2015-11-19T19:42:19.224
# start of a day
now.with(LocalTime.MIN); # 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); # 2015-11-19T00:00
If you do not need time-of-day (hour, minute, second etc. parts) consider using LocalDate class.
LocalDate.now(); # 2015-11-19
Here are couple of utility functions I use to do just this.
/**
* sets all the time related fields to ZERO!
*
* #param date
*
* #return Date with hours, minutes, seconds and ms set to ZERO!
*/
public static Date zeroTime( final Date date )
{
return DateTimeUtil.setTime( date, 0, 0, 0, 0 );
}
/**
* Set the time of the given Date
*
* #param date
* #param hourOfDay
* #param minute
* #param second
* #param ms
*
* #return new instance of java.util.Date with the time set
*/
public static Date setTime( final Date date, final int hourOfDay, final int minute, final int second, final int ms )
{
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime( date );
gc.set( Calendar.HOUR_OF_DAY, hourOfDay );
gc.set( Calendar.MINUTE, minute );
gc.set( Calendar.SECOND, second );
gc.set( Calendar.MILLISECOND, ms );
return gc.getTime();
}
One more JAVA 8 way:
LocalDateTime localDateTime = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
But it's a lot more useful to edit the date that already exists.
See the below code:
String datePattern24Hrs = "yyyy-MM-dd HH:mm:ss";
String datePattern12Hrs = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat simpleDateFormat24Hrs = new SimpleDateFormat(datePattern24Hrs);
SimpleDateFormat simpleDateFormat12Hrs = new SimpleDateFormat(datePattern12Hrs);
Date dateNow = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateNow);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date dateTime = calendar.getTime();
String dateTimeIn24Hrs = simpleDateFormat24Hrs.format(dateTime);
String dateTimeIn12Hrs = simpleDateFormat12Hrs.format(dateTime);
System.out.println("DateTime in 24Hrs: ".concat(dateTimeIn24Hrs));
System.out.println("DateTime in 12Hrs: ".concat(dateTimeIn12Hrs));
The expected output is as below:
DateTime in 24Hrs: 2021-06-29 00:00:00
DateTime in 12Hrs: 2021-06-29 12:00:00
I hope it helps with the answer you are looking for.
You would better to primarily set time zone to the DateFormat component like this:
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
Then you can get "00:00:00" time by passing 0 milliseconds to formatter:
String time = dateFormat.format(0);
or you can create Date object:
Date date = new Date(0); // also pass milliseconds
String time = dateFormat.foramt(date);
or you be able to have more possibilities using Calendar component but you should also set timezone as GMT to calendar instance:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 37);
calendar.set(Calendar.SECOND, 27);
dateFormat.format(calendar.getTime());
tl;dr
myJavaUtilDate // The terrible `java.util.Date` class is now legacy. Use *java.time* instead.
.toInstant() // Convert this moment in UTC from the legacy class `Date` to the modern class `Instant`.
.atZone( ZoneId.of( "Africa/Tunis" ) ) // Adjust from UTC to the wall-clock time used by the people of a particular region (a time zone).
.toLocalDate() // Extract the date-only portion.
.atStartOfDay( ZoneId.of( "Africa/Tunis" ) ) // Determine the first moment of that date in that zone. The day does *not* always start at 00:00:00.
java.time
You are using terrible old date-time classes that were supplanted years ago by the modern java.time classes defined in JSR 310.
Date ➙ Instant
A java.util.Date represent a moment in UTC. Its replacement is Instant. Call the new conversion methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Time zone
Specify the time zone in which you want your new time-of-day to make sense.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime
Apply the ZoneId to the Instant to get a ZonedDateTime. Same moment, same point on the timeline, but different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Changing time-of-day
You asked to change the time-of-day. Apply a LocalTime to change all the time-of-day parts: hour, minute, second, fractional second. A new ZonedDateTime is instantiated, with values based on the original. The java.time classes use this immutable objects pattern to provide thread-safety.
LocalTime lt = LocalTime.of( 15 , 30 ) ; // 3:30 PM.
ZonedDateTime zdtAtThreeThirty = zdt.with( lt ) ;
First moment of day
But you asked specifically for 00:00. So apparently you want the first moment of the day. Beware: some days in some zones do not start at 00:00:00. They may start at another time such as 01:00:00 because of anomalies such as Daylight Saving Time (DST).
Let java.time determine the first moment. Extract the date-only portion. Then pass the time zone to get first moment.
LocalDate ld = zdt.toLocalDate() ;
ZonedDateTime zdtFirstMomentOfDay = ld.atStartOfDay( z ) ;
Adjust to UTC
If you need to go back to UTC, extract an Instant.
Instant instant = zdtFirstMomentOfDay.toInstant() ;
Instant ➙ Date
If you need a java.util.Date to interoperate with old code not yet updated to java.time, convert.
java.util.Date d = java.util.Date.from( instant ) ;
As Java8 add new Date functions, we can do this easily.
// If you have instant, then:
Instant instant1 = Instant.now();
Instant day1 = instant1.truncatedTo(ChronoUnit.DAYS);
System.out.println(day1); //2019-01-14T00:00:00Z
// If you have Date, then:
Date date = new Date();
Instant instant2 = date.toInstant();
Instant day2 = instant2.truncatedTo(ChronoUnit.DAYS);
System.out.println(day2); //2019-01-14T00:00:00Z
// If you have LocalDateTime, then:
LocalDateTime dateTime = LocalDateTime.now();
LocalDateTime day3 = dateTime.truncatedTo(ChronoUnit.DAYS);
System.out.println(day3); //2019-01-14T00:00
String format = day3.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
System.out.println(format);//2019-01-14T00:00:00
Another simple way,
final Calendar today = Calendar.getInstance();
today.setTime(new Date());
today.clear(Calendar.HOUR_OF_DAY);
today.clear(Calendar.HOUR);
today.clear(Calendar.MINUTE);
today.clear(Calendar.SECOND);
today.clear(Calendar.MILLISECOND);
Doing this could be easier (In Java 8)
LocalTime.ofNanoOfDay(0)
Before Java 8:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
After Java 8:
LocalDateTime.now().with(LocalTime.of(0, 0, 0))
Another way to do this would be to use a DateFormat without any seconds:
public static Date trim(Date date) {
DateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Date trimmed = null;
try {
trimmed = format.parse(format.format(date));
} catch (ParseException e) {} // will never happen
return trimmed;
}
You can either do this with the following:
Calendar cal = Calendar.getInstance();
cal.set(year, month, dayOfMonth, 0, 0, 0);
Date date = cal.getTime();
If you need format 00:00:00 in string, you should use SimpleDateFormat as below. Using "H "instead "h".
Date today = new Date();
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
//not SimpleDateFormat("dd-MM-yyyy hh:mm:ss")
Calendar calendarDM = Calendar.getInstance();
calendarDM.setTime(today);
calendarDM.set(Calendar.HOUR, 0);
calendarDM.set(Calendar.MINUTE, 0);
calendarDM.set(Calendar.SECOND, 0);
System.out.println("Current Date: " + ft.format(calendarDM.getTime()));
//Result is: Current Date: 29-10-2018 00:00:00
Related
Supposing the time zone is CST. I have a webservice that returns a java.util.Date as "2020-03-14". I want to convert it to OffsetDateTime in the format "2020-03-14 05:59:59.9999990 +00:00". The below code does not have the time information.
Date endDate = someService.getEndDate();
Instant instant = Instant.ofEpochMilli(endDate.getTime());
OffsetDateTime offsetEndDt = OffsetDateTime.ofInstant(instant, ZoneOffset.UTC);
The value of offsetEndDt is 2020-03-14T05:00Z
An OffsetDateTime does not have any format itself, it holds the information about the date and the time. If you create an OffsetDateTime just from a date it will get the default time information of 0 hours, minutes, seconds and nanos.
You can output it in various formats using a DateTimeFormatter and create a new instance of OffsetDateTime adding temporal units to an existing one like this:
public static void main(String[] args) {
// example OffsetDateTime
OffsetDateTime offsetEndDt = OffsetDateTime.of(2020, 3, 14, 0, 0, 0, 0,
ZoneOffset.UTC);
// define a formatter for the output
DateTimeFormatter myFormatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.nnnnnnnnn xxx");
// print it using the previously defined formatter
System.out.println(offsetEndDt.format(myFormatter));
// create a new OffsetDateTime with time information
OffsetDateTime realEndOfDay = offsetEndDt
.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999999000);
// print that, too
System.out.println(realEndOfDay.format(myFormatter));
}
It produces the following output using the pattern your example desired output has:
2020-03-14T00:00:00.000000000 +00:00
2020-03-14T23:59:59.999999000 +00:00
First allow me to suggest that you represent the end of your interval NOT as one microsecond before the next day begins, but AS the first moment of the next day exclusive. So a point in time is inside your interval if it is strictly before your end time. This is philosophically more correct. And it rules out the possibility of falsely excluding a point in time within the last 999 nanoseconds of the day from your interval.
// Construct an example java.util.Date for the demonstration
Instant exampleInstant = LocalDate.of(2020, Month.MARCH, 14)
.atStartOfDay(ZoneId.systemDefault())
.toInstant();
Date enddt = Date.from(exampleInstant);
System.out.println("Example java.util.Date: " + enddt);
OffsetDateTime edt = enddt.toInstant()
.atZone(ZoneId.systemDefault())
.plusDays(1)
.truncatedTo(ChronoUnit.DAYS)
.toOffsetDateTime();
System.out.println("End: " + edt);
As one interpretation of EST (of several possible) I have run this code in America/Atikokan time zone (America/Winnipeg gave me EDT). The output was:
Example java.util.Date: Sat Mar 14 00:00:00 EST 2020
End: 2020-03-15T00:00-05:00
If you insist on getting the time 1 microsecond before the new day starts, subtract a microsecond:
OffsetDateTime edt = enddt.toInstant()
.atZone(ZoneId.systemDefault())
.plusDays(1)
.truncatedTo(ChronoUnit.DAYS)
.minus(1, ChronoUnit.MICROS)
.toOffsetDateTime();
End: 2020-03-14T23:59:59.999999-05:00
The below lines of code worked.
Date enddt = someService.getEndDate();
Calendar cal = Calendar.getInstance();
cal.setTime(enddt);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
OffsetDateTime edt = OffsetDateTime.of(year,month+1,day,23,59,59,999999000,OffsetDateTime.now().toZonedDateTime().getOffset());
I have a class that when its initialized, it records the time of initialization in a private field with a public getter:
public class TestClass {
private long mTimestamp;
public TestClass(){
mTimestamp = System.getCurrentMillis();
}
public long getTimestamp(){
return mTimestamp;
}
}
I also have an enum with the name of days:
public enum Days implements Serializable {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
Now the problem is in another class I have to get the timestamp and set a Days field to the day that the class was initialized:
public class OtherClass {
public Days getDayOfInitialization(TestClass testClass){
//how to do this?
Date date = new Date(testClass.getTimestamp())
Days day = Date.getDay(); //Deprecated!
//convert to enum and return...
}
}
The getDay() method of Date is deprecated...how should I do this?
If you just need the current day of week in a human-readable format, formatted to the current user's locale, then you could use this:
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
String dayString = sdf.format(new Date());
If their locale is "en_US", the output is:
Wednesday
If their locale is "de_DE", the output is:
Mittwoch
If their locale is "fr_FR", the output is:
mercredi
But if you need a numerical representation of the day of week (for example, you wanted to get '1' if it is Sunday or '2' if it is Monday), then you could use Calendar:
Calendar cal = Calendar.getInstance();
int dayInt = cal.get(Calendar.DAY_OF_WEEK);
use Calendar:
long timeStamp = testClass.getTimestamp();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(timeStamp);
int dayNum = c.get(Calendar.DAY_OF_WEEK);
Days day = Days.values()[dayNum];
return day;
Standard Week
You do not need that Enum as the standard for date-time (ISO 8601) defines a week as Monday to Sunday.
Joda-Time defines constants for each day-of-week name in English such as DateTimeConstants.MONDAY.
Avoid java.util.Date
You should be using Joda-Time library, as the java.util.Date and .Calendar classes are notoriously troublesome. Joda-Time works in Android according to others.
Avoid Milliseconds As Date-Time
Tracking date-time as milliseconds is less than optimal. Serializing to a ISO 8601 string is preferable. But if you must, so be it.
Time Zone Is Crucial
Time zone is crucial. Day-of-week is defined by time zone, as the comments above discussed.
If you want UTC, Joda-Time provides the constant DateTimeZone.UTC.
Joda-Time
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( millisSinceEpochInUtc, timeZone );
int dayOfWeekNumber = dateTime.getDayOfWeek(); // ISO 8601 standard says Monday is 1.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "EEEE" ).withLocale( java.util.Locale.ENGLISH );
String dayOfWeekName = formatter.print( dateTime );
You should use Calendar.getInstance() method, which provide a calendar based on System Settings' TimeZone
Calendar now = Calendar.getInstance();
Then get the day of the week as an int (1 = Sunday, 2 = Monday, and so on...)
int day = now.get(Calendar.DAY_OF_WEEK);
The records are getting saved according to time zone of US but if I want to show the same record back to user it should convert the server date time with(US Time Zone) to user's date time with user's Time Zone
If you type in google "Java date change timezone" or "Javascript date change timezone". You will have one of your results:
In Java (source: http://www.coderanch.com/t/417443/java/java/Convert-Date-one-timezone-another )
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("CET"));
// Prints the date in the CET timezone
System.out.println(formatter.format(date));
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("IST"));
// Prints the date in the IST timezone
System.out.println(formatter.format(date));
Javascript (source: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329 )
// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {
// create Date object for current location
d = new Date();
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
// get Bombay time
alert(calcTime('Bombay', '+5.5'));
java.time
The old date-time classes are poorly designed, confusing, and troublesome. Avoid them.
Use modern classes: the java.time framework built into Java 8 and later. Find back-ports for earlier Java 6 & 7 and for Android.
An Instant is a moment on the timeline in UTC.
Instant now = Instant.now();
Apply a time zone (ZoneId) to get a ZonedDateTime.
Never use the 3-4 letter zone abbreviations such as EST or IST. They are neither standardized nor unique(!). Use proper time zone names, built in a continent/region format such as Asia/Kolkata, Pacific/Auckland, America/Los_Angeles.
ZoneId zoneId_Montreal = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt_Montreal = ZonedDateTime.ofInstant( instant , zoneId_Montreal );
Apply a different time zone to generate another ZonedDateTime adjusted to that time zone. Call withZoneSameInstant.
ZoneId zoneId_Paris = ZoneId.of( "Europe/Paris" ); // Or "Asia/Kolkata", etc.
ZonedDateTime zdt_Paris = zdt_Montreal.withZoneSameInstant( zoneId_Paris );
If you want to go back to UTC, ask for an Instant.
Instant instant = zdt_Paris.toInstant();
TimeZone fromTimezone =TimeZone.getTimeZone(from);
TimeZone toTimezone=TimeZone.getTimeZone(to);
long fromOffset = fromTimezone.getOffset(calendar.getTimeInMillis());
long toOffset = toTimezone.getOffset(calendar.getTimeInMillis());
long convertedTime = calendar.getTimeInMillis() - (fromOffset - toOffset);
//Convert date from one zone to another
/*
$zone_from='Asia/Kolkata';
$zone_to='America/Phoenix';
date_default_timezone_set($zone_from);
$convert_date="2016-02-26 10:35:00";
echo $finalDate=zone_conversion_date($convert_date, $zone_from, $zone_to);
*/
function zone_conversion_date($time, $cur_zone, $req_zone)
{
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s");
date_default_timezone_set($cur_zone);
$local = date("Y-m-d H:i:s");
date_default_timezone_set($req_zone);
$required = date("Y-m-d H:i:s");
/* return $required; */
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
return $timestamp = $date->format("Y-m-d H:i:s");
}
Code To Get Berlin Time and Convert it into UTC Time
Calendar sc = Calendar.getInstance(TimeZone.getTimeZone("Europe/Berlin"));
String strt = null;
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
sf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
sc.set(sc.get(Calendar.YEAR),sc.get(Calendar.MONTH), sc.get(Calendar.DATE),sc.get(Calendar.HOUR) , sc.get(Calendar.MINUTE));
strt = sf.format(sc.getTime());
System.out.println("Start :"+strt);
I need a Java program to get the current date without a timestamp:
Date d = new Date();
gives me date and timestamp.
But I need only the date, without a timestamp. I use this date to compare with another date object that does not have a timestamp.
On printing
System.out.println("Current Date : " + d)
of d it should print May 11 2010 - 00:00:00.
A java.util.Date object is a kind of timestamp - it contains a number of milliseconds since January 1, 1970, 00:00:00 UTC. So you can't use a standard Date object to contain just a day / month / year, without a time.
As far as I know, there's no really easy way to compare dates by only taking the date (and not the time) into account in the standard Java API. You can use class Calendar and clear the hour, minutes, seconds and milliseconds:
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.AM_PM);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
Do the same with another Calendar object that contains the date that you want to compare it to, and use the after() or before() methods to do the comparison.
As explained into the Javadoc of java.util.Calendar.clear(int field):
The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
edit - The answer above is from 2010; in Java 8, there is a new date and time API in the package java.time which is much more powerful and useful than the old java.util.Date and java.util.Calendar classes. Use the new date and time classes instead of the old ones.
You could always use apache commons' DateUtils class. It has the static method isSameDay() which "Checks if two date objects are on the same day ignoring time."
static boolean isSameDay(Date date1, Date date2)
Use DateFormat to solve this problem:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateFormat2 = new SimpleDateFormat("MM-dd-yyyy");
print(dateFormat.format(new Date()); // will print like 2014-02-20
print(dateFormat2.format(new Date()); // will print like 02-20-2014
I did as follows and it worked: (Current date without timestamp)
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date today = dateFormat.parse(dateFormat.format(new Date()));
DateFormat dateFormat = new SimpleDateFormat("MMMM dd yyyy");
java.util.Date date = new java.util.Date();
System.out.println("Current Date : " + dateFormat.format(date));
You can get by this date:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
print(dateFormat.format(new Date());
You could use
// Format a string containing a date.
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;
Calendar c = GregorianCalendar.getInstance();
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"
Have a look at the Formatter API documentation.
The accepted answer by Jesper is correct but now outdated. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
java.time
Instead use the java.time framework, built into Java 8 and later, back-ported to Java 6 & 7 and further adapted to Android.
If you truly do not care about time-of-day and time zones, use LocalDate in the java.time framework ().
LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );
Today
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 you want to use the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault(). If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
LocalDate today = LocalDate.now( z ) ;
Moment
If you care about specific moments, specific points on the timeline, do not use LocalDate. If you care about the date as seen through the wall-clock time used by the people of a certain region, do not use LocalDate.
Be aware that if you have any chance of needing to deal with other time zones or UTC, this is the wrong way to go. Naïve programmers tend to think they do not need time zones when in fact they do.
Strings
Call toString to generate a string in standard ISO 8601 format.
String output = localDate.toString();
2014-05-06
For other formats, search Stack Overflow for DateTimeFormatter class.
Joda-Time
Though now supplanted by java.time, you can use the similar LocalDate class in the Joda-Time library (the inspiration for java.time).
LocalDate localDate = new LocalDate( 2014, 5, 6 );
Also you can use apache commons lib DateUtils.truncate():
Date now = new Date();
Date truncated = DateUtils.truncate(now, Calendar.DAY_OF_MONTH);
Time will be set to 00:00:00 so you can work with this date or print it formatted:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(now); // 2010-05-11 11:32:47
System.out.println(dateFormat.format(truncated); // 2010-05-11 00:00:00
private static final DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
private static Date NOW = new Date();
static {
try {
NOW = df1.parse(df1.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
}
I think this will work. Use Calendar to manipulate time fields (reset them to zero), then get the Date from the Calendar.
Calendar c = GregorianCalendar.getInstance();
c.clear( Calendar.HOUR_OF_DAY );
c.clear( Calendar.MINUTE );
c.clear( Calendar.SECOND );
c.clear( Calendar.MILLISECOND );
Date today = c.getTime();
Or do the opposite. Put the date you want to compare to in a calendar and compare calendar dates
Date compareToDate; // assume this is set before going in.
Calendar today = GregorianCalendar.getInstance();
Calendar compareTo = GregorianCalendar.getInstance();
compareTo.setTime( compareToDate );
if( today.get( Calendar.YEAR ) == compareTo.get( Calendar.YEAR ) &&
today.get( Calendar.DAY_OF_YEAR ) == compareTo.get( Calendar.DAY_OF_YEAR ) ) {
// They are the same day!
}
Here's an inelegant way of doing it quick without additional dependencies.
You could just use java.sql.Date, which extends java.util.Date although for comparisons you will have to compare the Strings.
java.sql.Date dt1 = new java.sql.Date(System.currentTimeMillis());
String dt1Text = dt1.toString();
System.out.println("Current Date1 : " + dt1Text);
Thread.sleep(2000);
java.sql.Date dt2 = new java.sql.Date(System.currentTimeMillis());
String dt2Text = dt2.toString();
System.out.println("Current Date2 : " + dt2Text);
boolean dateResult = dt1.equals(dt2);
System.out.println("Date comparison is " + dateResult);
boolean stringResult = dt1Text.equals(dt2Text);
System.out.println("String comparison is " + stringResult);
Output:
Current Date1 : 2010-05-10
Current Date2 : 2010-05-10
Date comparison is false
String comparison is true
If you really want to use a Date instead for a Calendar for comparison, this is the shortest piece of code you could use:
Calendar c = Calendar.getInstance();
Date d = new GregorianCalendar(c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).getTime();
This way you make sure the hours/minute/second/millisecond values are blank.
I did as follows and it worked:
calendar1.set(Calendar.HOUR_OF_DAY, 0);
calendar1.set(Calendar.AM_PM, 0);
calendar1.set(Calendar.HOUR, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);
Date date1 = calendar1.getTime(); // Convert it to date
Do this for other instances to which you want to compare. This logic worked for me; I had to compare the dates whether they are equal or not, but you can do different comparisons (before, after, equals, etc.)
I was looking for the same solution and the following worked for me.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.clear(Calendar.HOUR);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
Date today = calendar.getTime();
Please note that I am using calendar.set(Calendar.HOUR_OF_DAY, 0) for HOUR_OF_DAY instead of using the clear method, because it is suggested in Calendar.clear method's javadocs as the following
The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and
the the resolution rule for the time of day is applied. Clearing one
of the fields doesn't reset the hour of day value of this Calendar.
Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
With the above posted solution I get output as
Wed Sep 11 00:00:00 EDT 2013
Using clear method for HOUR_OF_DAY resets hour at 12 when executing after 12PM or 00 when executing before 12PM.
Here is my code for get only date:
Calendar c=Calendar.getInstance();
DateFormat dm = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date = new java.util.Date();
System.out.println("current date is : " + dm.format(date));
Here is full Example of it.But you have to cast Sting back to Date.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO OutPut should LIKE in this format MM dd yyyy HH:mm:ss.SSSSSS
public class TestDateExample {
public static void main(String args[]) throws ParseException {
SimpleDateFormat changeFormat = new SimpleDateFormat("MM dd yyyy HH:mm:ss.SSSSSS");
Date thisDate = new Date();//changeFormat.parse("10 07 2012");
System.out.println("Current Date : " + thisDate);
changeFormat.format(thisDate);
System.out.println("----------------------------");
System.out.println("After applying formating :");
String strDateOutput = changeFormat.format(thisDate);
System.out.println(strDateOutput);
}
}
I need to compare two Dates (e.g. date1 and date2) and come up with a boolean sameDay which is true of the two Dates share the same day, and false if they are not.
How can I do this? There seems to be a whirlwind of confusion here... and I would like to avoid pulling in other dependencies beyond the JDK if at all possible.
to clarify: if date1 and date2 share the same year, month, and day, then sameDay is true, otherwise it is false. I realize this requires knowledge of a timezone... it would be nice to pass in a timezone but I can live with either GMT or local time as long as I know what the behavior is.
again, to clarify:
date1 = 2008 Jun 03 12:56:03
date2 = 2008 Jun 03 12:59:44
=> sameDate = true
date1 = 2009 Jun 03 12:56:03
date2 = 2008 Jun 03 12:59:44
=> sameDate = false
date1 = 2008 Aug 03 12:00:00
date2 = 2008 Jun 03 12:00:00
=> sameDate = false
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);
Note that "same day" is not as simple a concept as it sounds when different time zones can be involved. The code above will for both dates compute the day relative to the time zone used by the computer it is running on. If this is not what you need, you have to pass the relevant time zone(s) to the Calendar.getInstance() calls, after you have decided what exactly you mean with "the same day".
And yes, Joda Time's LocalDate would make the whole thing much cleaner and easier (though the same difficulties involving time zones would be present).
How about:
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(date1).equals(fmt.format(date2));
You can also set the timezone to the SimpleDateFormat, if needed.
I use the "apache commons lang" package to do this (namely org.apache.commons.lang.time.DateUtils)
boolean samedate = DateUtils.isSameDay(date1, date2); //Takes either Calendar or Date objects
You can avoid external dependencies and the performance hit of using Calendar by calculating the Julian Day Number for each of the dates and then comparing these:
public static boolean isSameDay(Date date1, Date date2) {
// Strip out the time part of each date.
long julianDayNumber1 = date1.getTime() / MILLIS_PER_DAY;
long julianDayNumber2 = date2.getTime() / MILLIS_PER_DAY;
// If they now are equal then it is the same day.
return julianDayNumber1 == julianDayNumber2;
}
Joda-Time
As for adding a dependency, I'm afraid the java.util.Date & .Calendar really are so bad that the first thing I do to any new project is add the Joda-Time library. In Java 8 you can use the new java.time package, inspired by Joda-Time.
The core of Joda-Time is the DateTime class. Unlike java.util.Date, it understands its assigned time zone (DateTimeZone). When converting from j.u.Date, assign a zone.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeQuébec = new DateTime( date , zone );
LocalDate
One way to verify if two date-times land on the same date is to convert to LocalDate objects.
That conversion depends on the assigned time zone. To compare LocalDate objects, they must have been converted with the same zone.
Here is a little utility method.
static public Boolean sameDate ( DateTime dt1 , DateTime dt2 )
{
LocalDate ld1 = new LocalDate( dt1 );
// LocalDate determination depends on the time zone.
// So be sure the date-time values are adjusted to the same time zone.
LocalDate ld2 = new LocalDate( dt2.withZone( dt1.getZone() ) );
Boolean match = ld1.equals( ld2 );
return match;
}
Better would be another argument, specifying the time zone rather than assuming the first DateTime object’s time zone should be used.
static public Boolean sameDate ( DateTimeZone zone , DateTime dt1 , DateTime dt2 )
{
LocalDate ld1 = new LocalDate( dt1.withZone( zone ) );
// LocalDate determination depends on the time zone.
// So be sure the date-time values are adjusted to the same time zone.
LocalDate ld2 = new LocalDate( dt2.withZone( zone ) );
return ld1.equals( ld2 );
}
String Representation
Another approach is to create a string representation of the date portion of each date-time, then compare strings.
Again, the assigned time zone is crucial.
DateTimeFormatter formatter = ISODateTimeFormat.date(); // Static method.
String s1 = formatter.print( dateTime1 );
String s2 = formatter.print( dateTime2.withZone( dt1.getZone() ) );
Boolean match = s1.equals( s2 );
return match;
Span of Time
The generalized solution is to define a span of time, then ask if the span contains your target. This example code is in Joda-Time 2.4. Note that the "midnight"-related classes are deprecated. Instead use the withTimeAtStartOfDay method. Joda-Time offers three classes to represent a span of time in various ways: Interval, Period, and Duration.
Using the "Half-Open" approach where the beginning of the span is inclusive and the ending exclusive.
The time zone of the target can be different than the time zone of the interval.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime target = new DateTime( 2012, 3, 4, 5, 6, 7, timeZone );
DateTime start = DateTime.now( timeZone ).withTimeAtStartOfDay();
DateTime stop = start.plusDays( 1 ).withTimeAtStartOfDay();
Interval interval = new Interval( start, stop );
boolean containsTarget = interval.contains( target );
java.time
Java 8 and later comes with the java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project. See Tutorial.
The makers of Joda-Time have instructed us all to move to java.time as soon as is convenient. In the meantime Joda-Time continues as an actively maintained project. But expect future work to occur only in java.time and ThreeTen-Extra rather than Joda-Time.
To summarize java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime object. To move off the timeline, to get the vague indefinite idea of a date-time, use the "local" classes: LocalDateTime, LocalDate, LocalTime.
The logic discussed in the Joda-Time section of this Answer applies to java.time.
The old java.util.Date class has a new toInstant method for conversion to java.time.
Instant instant = yourJavaUtilDate.toInstant(); // Convert into java.time type.
Determining a date requires a time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
We apply that time zone object to the Instant to obtain a ZonedDateTime. From that we extract a date-only value (a LocalDate) as our goal is to compare dates (not hours, minutes, etc.).
ZonedDateTime zdt1 = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate localDate1 = LocalDate.from( zdt1 );
Do the same to the second java.util.Date object we need for comparison. I’ll just use the current moment instead.
ZonedDateTime zdt2 = ZonedDateTime.now( zoneId );
LocalDate localDate2 = LocalDate.from( zdt2 );
Use the special isEqual method to test for the same date value.
Boolean sameDate = localDate1.isEqual( localDate2 );
Convert dates to Java 8 java.time.LocalDate
as seen here.
LocalDate localDate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate localDate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// compare dates
assertTrue("Not on the same day", localDate1.equals(localDate2));
Java 8
If you are using Java 8 in your project and comparing java.sql.Timestamp, you could use the LocalDate class:
sameDate = date1.toLocalDateTime().toLocalDate().equals(date2.toLocalDateTime().toLocalDate());
If you are using java.util.Date, have a look at Istvan answer which is less ambiguous.
private boolean isSameDay(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
return (sameDay && sameMonth && sameYear);
}
FOR ANDROID USERS:
You can use DateUtils.isToday(dateMilliseconds) to check whether the given date is current day or not.
API reference: https://developer.android.com/reference/android/text/format/DateUtils.html#isToday(long)
For Kotlin devs this is the version with comparing formatted strings approach:
val sdf = SimpleDateFormat("yyMMdd")
if (sdf.format(date1) == sdf.format(date2)) {
// same day
}
It's not the best way, but it's short and working.
in addition to Binil Thomas solution
public static boolean isOnSameDay(Timestamp... dates) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
String date1 = fmt.format(dates[0]);
for (Timestamp date : dates) {
if (!fmt.format(date).equals(date1)) {
return false;
}
}
return true;
}
usage
isOnSameDay(date1,date2,date3 ...);
//or
isOnSameDay(mydates);
With JAVA 8 we can convert Date object to LocalDate object, hence we can do this:
public static boolean isDatesAreDifferentDays(Date date1,Date date2)
{
LocalDate d1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate d2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
if(d1.getDayOfMonth() != d2.getDayOfMonth())
{
return false;
}
else if(d1.getMonth() != d2.getMonth())
{
return false;
}
else if(d1.getYear() != d2.getYear())
{
return false;
}
else
{
return true;
}
}
FASTER SOLUTION
Like #AyeJay solution but correct for all timezones, that add a offset in timestamp.
public static boolean isSameDay(Date dateA, Date dateB) {
int offset = TimeZone.getDefault().getRawOffset();
try {
long julianDayNumber1 = (dateA.getTime() + offset) / MILLIS_PER_DAY;
long julianDayNumber2 = (dateB.getTime() + offset) / MILLIS_PER_DAY;
return julianDayNumber1 == julianDayNumber2;
} catch (Exception e) {
return false;
}
}
you can apply the same logic as the SimpleDateFormat solution without relying on SimpleDateFormat
date1.getFullYear()*10000 + date1.getMonth()*100 + date1.getDate() ==
date2.getFullYear()*10000 + date2.getMonth()*100 + date2.getDate()