I have an SQLite database that has an integer column to store a unix time stamp and I need to be able to query this column for specific days.
I am looking for a method to return the Unix time for the beginning and end of a given day. What is the best way to do this?
Here is one way to do it.
public long getStartOfDayInMillis() {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
public long getEndOfDayInMillis() {
// Add one day's time to the beginning of the day.
// 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 1 day
return getStartOfDayInMillis() + (24 * 60 * 60 * 1000);
}
If you want the times for a specific date, you can modify the code to handle that.
/**
* #param date the date in the format "yyyy-MM-dd"
*/
public long getStartOfDayInMillis(String date) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(format.parse(date));
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTimeInMillis();
}
/**
* #param date the date in the format "yyyy-MM-dd"
*/
public long getEndOfDayInMillis(String date) throws ParseException {
// Add one day's time to the beginning of the day.
// 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 1 day
return getStartOfDayInMillis(date) + (24 * 60 * 60 * 1000);
}
Related
I copied code from the web for calculating the number of days between two dates. it often produces incorrect results. For example, The days between 01/15/2008 and 03/15/2010 are 790. The code returns 789. The days between 12/30/2013 and 02/28/2017 are 1156. The code returns 1152. Are the errors due to the code or Calendar class? I am copying the code below. This is my first post and I apologize for any protocol errors.
Thanks,
Nick
import java.util.Calendar;
public class DateExperiment2
{
public static void main(String args[]) throws Exception
{
// Create Calendar instances
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
// Set the values for the calendar fields YEAR, MONTH, and DAY_OF_MONTH.
calendar1.set(2008, 1, 15);
calendar2.set(2010, 3, 15);
//Get Calendars' time value in milliseconds
long miliSecondForDate1 = calendar1.getTimeInMillis();
long miliSecondForDate2 = calendar2.getTimeInMillis();
// Calculate the difference in millisecond between two dates
long diffInMilis = miliSecondForDate1 - miliSecondForDate2;
//Convert milliseconds to days
long diffInDays = diffInMilis / (24 * 60 * 60 * 1000);
System.out.println(diffInDays);
}
}
The results and the is good
But when you set month on 01
`Calendar.Set(2000,1,15)`
That means you set it on 15 February 2000
Month on Calender start from 0
0 =is January
1= February...
I have the current date and I want to get the date which is 1 year back by using only java.util.Date
I'm working in gwt so cannot use SimpleDateFormat or Calendar
Date currentDate = new Date();
Date oneYearBefore = new Date( - (365 * 24 * 60 * 60 * 1000));
The above mentioned code is not working (got it from some forum)
Use Calendar class
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);
System.out.println(calendar.getTime());
You are using all int's, when you multiply them you get an int. You're converting that int to a long, but only after the int multiplication has already resulted in the wrong answer.
Actually it is overflowing the int type
public static void main(String[] args) {
Date currentDate = new Date();
System.out.println(currentDate);
long milliseconds = (long) 365 * 24 * 60 * 60 * 1000;
Date oneYearBefore = new Date(currentDate.getTime() - milliseconds);
System.out.println(oneYearBefore);
}
Mon Nov 17 13:11:10 IST 2014
Sun Nov 17 13:11:10 IST 2013
Why You cannot use Calendar? I think You might have misunderstood something?
anyways:
Date oneYearBefore = new Date( System.currentTimeMillis() - (365 * 24 * 60 * 60 * 1000));
Or by using Your code pasted from the forum:
Date currentDate = new Date();
Date oneYearBefore = new Date( currentDate.getTime() - (365 * 24 * 60 * 60 * 1000));
Using only java.util.Date, you can use:
Date oneYearBefore = new Date(currentDate.getTime() - (365L * 24L * 60L * 60L * 1000L));
But keep in mind, this doesn't account for potential leap years.
I ma trying to write a Junit for the following code;
/**
* Check if a date is greater than 24 hours
* #param dateToCheck the date to check
* #return true if it is greater than otherwise false
*/
public static boolean dateGreaterThan24Hours(Date dateToCheck){
if(dateToCheck == null){
throw new IllegalArgumentException("The date passed to check for greater than 24 hours is null");
}
long millisIn24Hours = 1000 * 60 * 60 * 24;
Date hours24ago = new Date(new Date().getTime() - millisIn24Hours);
if (dateToCheck.before(hours24ago)) {
//24 hrs have passed
return true;
}
return false;
}
However I am struggling to do so because the method only accepts a date to check against. Meaning y current attempt at a test method is clearly going to fail;
#Test
public void checkLessThan24HoursShouldReturnTrue(){
//Calendar represents the 7th of July 2014 at 17.30pm
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 07);
cal.set(Calendar.DAY_OF_MONTH, 7);
cal.set(Calendar.HOUR_OF_DAY,17);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Date july7 = cal.getTime();
//Calendar represents the 6th of July 2014 at 18.30pm
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 07);
cal.set(Calendar.DAY_OF_MONTH, 6);
cal.set(Calendar.HOUR_OF_DAY,18);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Date july6 = cal.getTime();
}
Can anyone suggest how i can refactor the original method to make it easier to test?
Thanks
You don't have to change the original method. The easiest tests to write would be:
#Test
public void checkMoreThan24HoursShouldReturnTrue() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -25);
assertTrue(YourClass.dateGreaterThan24Hours(cal.getTime()));
}
#Test
public void checkLessThan24HoursShouldReturnFalse() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, -23);
assertFalse(YourClass.dateGreaterThan24Hours(cal.getTime()));
}
Also I would recommend some refactorings as suggested by #DaveNewton in the comments, and a test that verifies your custom exception for null argument.
If you can use the new Java 8 Classes (or JodaTime) you can write much cleaner code.
Plus, depending on why you want 24 hrs ago, there might be bugs regarding Daylight savings time since you only do 24 hrs as milliseconds which might not be a full day ago on certain days.
Here is the equivalent code using the new Java 8 time library. I renamed the method to be more intent revealing and added a Clock optional parameter that allows you to set the time for tests:
public static boolean checkDateMorethan24HrsOld(Date dateToCheck){
return checkDateMorethan24HrsOld(dateToCheck, Clock.systemDefaultZone());
}
public static boolean checkDateMorethan24HrsOld(Date dateToCheck, Clock clock){
if(dateToCheck == null){
//maybe throw NullPointerInstead?
throw new IllegalArgumentException("The date is null");
}
Objects.requireNonNull(clock);
//use clock.instant().minus(Period.ofDays(1)) to support DST
Instant time24HrsAgo =clock.instant().minus(Duration.ofHours(24));
return dateToCheck.toInstant().compareTo(time24HrsAgo) <0;
}
Then your test:
#Test
public void checkLessThan24HoursShouldReturnTrue(){
Instant clocktime = Instant.parse("2014-07-07T17:30:00Z");
Clock clock =Clock.fixed(clocktime, ZoneId.systemDefault());
assertTrue(checkDateMorethan24HrsOld(Date.from(clocktime.minus(Duration.ofDays(2))), clock));
assertFalse("exactly 24 hrs ago",
checkDateMorethan24HrsOld(Date.from(clocktime.minus(Duration.ofDays(1))), clock));
assertFalse(checkDateMorethan24HrsOld(Date.from(clocktime.minus(Duration.ofHours(1))), clock));
}
Of course this code is even simplier if the method takes an Instant instead of Date.
If you could refactor you code to be test friendly:
static final long millisIn24Hours = 1000 * 60 * 60 * 24;
public static boolean dateGreaterThan24Hours(Date dateToCheck){
return dateGreaterThan(dateToCheck,
Calendar.getInstance().getTime(), - millisIn24Hours);
}
public static boolean dateGreaterThan(Date date, Date than, long msDiff) {
if(date == null){
throw new IllegalArgumentException("date is null");
}
if(than == null){
throw new IllegalArgumentException("than is null");
}
return date.before(new Date(than.getTime() + msDiff));
}
You could have somethign like this:
public void testDateGreaterTrue() {
Date now = new Date();
assertFalse(dateGreaterThan(now,
new Date(now.getTime()-millisIn24Hours), millisIn24Hours));
}
public void testDateGreaterFalse() {
Date now = new Date();
assertFalse(dateGreaterThan(now,
new Date(now.getTime()-millisIn24Hours-1), millisIn24Hours));
}
Instead of:
public void testDateGreaterThan24HoursTrue() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) - 25);
assertTrue(dateGreaterThan24Hours(cal.getTime()));
}
public void testDateGreaterThan24HoursFalse() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, cal.get(Calendar.HOUR_OF_DAY) - 23);
cal.set(Calendar.MINUTE, cal.get(Calendar.MINUTE) + 59);
cal.set(Calendar.SECOND, cal.get(Calendar.SECOND) + 59);
assertFalse(dateGreaterThan24Hours(cal.getTime()));
}
In my Android app. I am running some Task every 2 hours.How can i check that the time has exceeded 2 hours.
I tried to use this but it says depreceated
Date date = new Date();
date.setHours(date.getHours() + 2);
I would appreciate the insight on how to implement this?
Check this link
http://www.dotnetexpertsforum.com/comparing-date-time-values-in-android-t1567.html
Calendar current_time = Calendar.getInstance ();
current_time.add(Calendar.YEAR, 0);
current_time.add(Calendar.DAY_OF_YEAR, 0);
current_time.set(Calendar.HOUR_OF_DAY,
//Subtract 2 hours
current_time.get(Calendar.HOUR_OF_DAY)-2);
current_time.set(Calendar.MINUTE, 0);
current_time.set(Calendar.SECOND, 0);
Calendar given_time = Calendar.getInstance ();
given_time.set(Calendar.YEAR, syear);
//Give the day sDay and hour shour
given_time.set(Calendar.DAY_OF_YEAR, sday);
given_time.set(Calendar.HOUR_OF_DAY, shour);
given_time.set(Calendar.MINUTE, 0 );
given_time.set(Calendar.SECOND, 0);
Date current_calendar = current_time.getTime();
Date given_calendar = given_time.getTime();
System.out.println("Current Calendar "+ current_calendar);
System.out.println("Given Calendar "+ given_calendar);
boolean v = current_calendar.after(given_calendar);
if(v){
return true;
}
You should use the Calendar class.
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY)+2);
calendar.getTime();//your date +2 hours
use Calendar class :
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.HOUR)>(cal.get(Calendar.HOUR)+2));
Date is deprecated. Use Calendar instead.
Source: Java: Why is the Date constructor deprecated, and what do I use instead?
Two hours is 2 * 60 minutes, is 2 * 60 * 60 seconds and is 2 * 60 * 60 * 1000 milliseconds. So you can just add this number of milliseconds to your date:
Date date = new Date ();
Date after2Hours = new Date (date.getTime () + 2L * 60L * 60L * 1000L);
If you have to repeat that task every two hours, you should use Alarm manager service for that. See the link below for more details.
http://www.javacodegeeks.com/2012/09/android-alarmmanager-tutorial.html
I have an application which use the current date and a date that is chose by user using date picker as follow:
If the date that the user chose is more than the current date +280 day,
some code will be executed.
If the date that the user chose is less than the current date , some
code will be executed.
I used this code to do so ..
Calendar start2 = Calendar.getInstance();
int birthYear = birthDayDatePicker.getYear();
int birthMonth = birthDayDatePicker.getMonth();
int birthDay = birthDayDatePicker.getDayOfMonth();
start2.set(birthYear, birthMonth, birthDay);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(birthDate);
cal2.add(Calendar.DAY_OF_MONTH,daysToAdd);
birthDayChosenCalender.set(birthYear,birthMonth,birthDay);
MaxBirthDayCalender.set(currentYear, currentMonth, currentDay);
long diff = birthDayChosenCalender.getTimeInMillis() - MaxBirthDayCalender.getTimeInMillis(); //result in millis
long daysBetween = diff / (24 * 60 * 60 * 1000);
System.out.println("Days between ,,,,,,,,,,,,,,,,,,"+daysBetween);
if(MaxBirthDayCalender.before(birthDayChosenCalender) && daysBetween <= 280){
do sth }
Is there any other clean way to do that ! because this way is not working well !
The other clean way to do it is to use the Joda Time library.
Other than that, everything can be done using millis and a single calendar instance:
Calendar pickedDate = new GregorianCalendar(
picker.getYear(),
picker.getMonth(),
picker.getDayOfMonth());
long pickedTime = pickedDate.getTimeInMillis();
long now = new Date().getTime();
if (pickedTime - now <= (280 * 24 * 60 * 60 * 1000)) { // 280 days in milliseconds
// ...
}
Should cover the requirement:
I have an application which use the current date and a date that is chose by user using date picker as follow:
If the date that the user chose is more than the current date +280 day, some code will be executed.
If the date that the user chose is less than the current date , some code will be executed.