Given the assignment t = System.currentTimeMillis(), accrued at some point in the past, how do I get the millis of the same day as t in 12 pm and the day after 12 pm?
Note: this is timezone dependent. You can do as such:
import static java.util.Calendar.*;
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(yourValue);
cal.set(HOUR_OF_DAY, 12);
cal.set(MINUTE, 0);
cal.set(SECOND, 0);
cal.set(MILLISECOND, 0);
// cal.getTimeInMillis() contains the wanted day at 12pm
cal.add(DAY_OF_YEAR, 1);
// cal.getTimeInMillis() now contains the wanted day plus one at 12pm
But do yourself a favour and use Joda Time, it is much easier to use in this case:
final DateTime dayAt12pm = new DateTime(yourValue).toDateMidnight()
.plusHours(12);
// dayAt12pm.getMillis() contains the wanted day at 12pm
// next day at 12pm: dayAt12pm.plusDays(1).getMillis()
//plug your "T" here.
long t = System.currentTimeMillis();
Date date = new Date(t);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar startOfDay = Calendar.getInstance();
startOfDay.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
startOfDay.set(Calendar.HOUR, 12);
startOfDay.set(Calendar.MINUTE, 0);
startOfDay.set(Calendar.SECOND, 0);
startOfDay.set(Calendar.MILLISECOND, 0);
Date startOfDayDate = startOfDay.getTime();
System.err.println("12PM on time t is " + startOfDayDate);
startOfDay.add(Calendar.HOUR, 24);
startOfDayDate = startOfDay.getTime();
System.err.println("12PM day after t is " + startOfDayDate);
One way would be to create a Date from it and then use the Calendar class.
Related
I am very confused on how I can convert a given time like 9:30pm into milliseconds because I need to run a code if it is past a certain time. I already know how to get the current time in milliseconds by the following code:
long timestamp = System.currentTimeMillis();
But how would I convert 9:30pm into milliseconds? I have been researching for hours now and I can only seem to find out how to get the current time.
My application needs to check if it is 9:30pm or past and if so, run a toast message.
The fastest and correct way to do it on Android is to use Calendar. You can make Calendar instance static and reuse it whenever you need it.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 9);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.AM_PM, Calendar.PM);
long timeInMillis = calendar.getTimeInMillis();
I do not need to check time in milliseconds, you can compare current time with desired values using Calendar class:
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
if (hour > 21 || (hour == 21 && minute >= 30)) {
doSomeJob();
}
Note that this code will not work after a midnight.
If you need time in milliseconds for 9:30pm today, you should use Calendar object to build date and time you need.
// init calendar with current date and default locale
Calendar cal = Calendar.getInstance(Locale.getDefault());
cal.setTime(new Date());
// set new time
cal.set(Calendar.HOUR_OF_DAY, 21);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
// obtain given time in ms
long today930PMinMills = cal.getTimeInMillis();
No need for milliseconds if you have a decent date-time library.
You can use the Joda-Time library on Android.
DateTime dateTime = new DateTime( 2014, 1, 2, 3, 4, 5 ); // Year, month, day, hour, minute, second.
boolean isNowAfterThatDateTime = DateTime.now().isAfter( dateTime );
Why don't you do it with a constant? You said that you need to check if is past 9;30. So convert that time to milliseconds and use it ad a constant. 21:30 = (21 * 60 + 30) * 60 * 1000 will give u the 9;30 in milliseconds to compare with the current time that u get in milliseconds
I need to get actual date with custom hour so I create this code:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
Calendar output = Calendar.getInstance();
output.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 1, 0);
output.getTime();
I hope it works but it seems a litle bit complicated.
Is there some other way how to get date with custom hour?
Is there some other way how to get date with custom hour ?
Personally I'd use Joda Time instead:
// Ideally use an injectable clock...
LocalDate today = new LocalDate();
// If this is effectively constant, extract it to a final static field
LocalTime time = new LocalTime(1, 0);
// Or use toDateTime(...) depending on what you're trying to accomplish
LocalDateTime todayAtTime = today.toLocalDateTime(time);
Joda Time has a much more pleasant API than java.util.{Date, Calendar}
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 1);
cal.set(Calendar.MINUTE, 0);
cal.getTime()
what about this :
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, your_custom_hour);
your_custom_hour : 0-23
Other than use Joda time I'd do it slightly cleaner:
int hour = 1;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Calendar.getInstance() returns the current date and time anyway so setTime(new Date()) is unnecessary.
The user entered date is using a drop down separately for day, month and year. I have to compare the user entered date with today's date and check if it is same day or future day. I am a bit confused about the time portion because I am not interested in time, just the date. How to solve this without using the Date class (I read it is not recommended to use Date class).
Thanks.
You first need to create GregorianCalendar instance representing entered date:
Calendar user = new GregorianCalendar(2012, Calendar.MAY, 17);
And one for "now":
Calendar now = new GregorianCalendar();
This will yield positive value if date is in the future and negative - if in the past:
user.compareTo(now);
Few notes about constructing user object:
it uses current JVM time zone, so in my case it is midnight, 17th of May in CEST time zone
be careful with months, they are 0-based
Try class DateUtils of library Apache Commons Lang.
This class provides the method truncatedEquals(cal1, cal2, field).
So you can check for equality with a single line of code:
Calendar user = new GregorianCalendar(2012, Calendar.MAY, 17);
Calendar now = Calendar.getInstance();
if(DateUtils.truncatedEquals(user, now, Calendar.DATE)){
// your code goes here
}
Simple calculation :
GregorianCalendar gc1 = new GregorianCalendar();
GregorianCalendar gc2 = new GregorianCalendar();
gc2.add(GregorianCalendar.DAY_OF_MONTH, 2); // gc2 is 2 days after gc1
long duration = (gc2.getTimeInMillis() - gc1.getTimeInMillis() )
/ ( 1000 * 60 * 60 * 24) ;
System.out.println(duration);
-> 2
Use a gregorian calendar.
If you wanted to know the number of days difference between two dates then you could make a method similar to the following.
public int getDays(GregorianCalendar g1, GregorianCalendar g2) {
int elapsed = 0;
GregorianCalendar gc1, gc2;
if (g2.after(g1)) {
gc2 = (GregorianCalendar) g2.clone();
gc1 = (GregorianCalendar) g1.clone();
}
else {
gc2 = (GregorianCalendar) g1.clone();
gc1 = (GregorianCalendar) g2.clone();
}
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
gc2.clear(Calendar.MILLISECOND);
gc2.clear(Calendar.SECOND);
gc2.clear(Calendar.MINUTE);
gc2.clear(Calendar.HOUR_OF_DAY);
while ( gc1.before(gc2) ) {
gc1.add(Calendar.DATE, 1);
elapsed++;
}
return elapsed;
}
That would return you the difference in the number of days.
Try this solution:
int day = 0; //user provided
int month = 0; //user provided
int year = 0; //user provided
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONDAY, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
long millisUser = calendar.getTime().getTime();
long nowMillis = System.currentTimeMillis();
if(nowMillis < millisUser) {
...
}
Above is check if date is in future.
There is nothing wrong in using java.util.Date
You can use:
int day = 0; //user provided
int month = 0; //user provided
int year = 0; //user provided
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONDAY, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
Date userSubmit = calendar.getTime();
Date now = new Date();
if(userSubmit.after(now)) {
...
}
But if you want fluent, easy and intuitive API with dates I recommend using JodaTime
I get the today's date like this:
final Calendar cal = Calendar.getInstance();
{
mYear = cal.get(Calendar.YEAR);
mMonth = cal.get(Calendar.MONTH);
mDay = cal.get(Calendar.DAY_OF_MONTH);
}
I want to calculate what was the date x days ago... anyone got something?
A better way would be to use add method instead of set:
cal.add(DAY_OF_YEAR, -2);
I.e. to be sure it works also the first day in month etc.
You can do the following :
Calendar cal=Calendar.getInstance();
int currentDay=cal.get(Calendar.DAY_OF_MONTH);
//Set the date to 2 days ago
cal.set(Calendar.DAY_OF_MONTH, currentDay-2);
then you can get the date :
cal.getTime(); //The date 2 days ago
I use the following fuction:
public static Date getStartOfDay() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new 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.getTime();
}
public static long getDaysAgo(Date date){
final long diff = getStartOfDay().getTime() - date.getTime();
if(diff < 0){
// if the input date millisecond > today's 12:00am millisecond it is today
// (this won't work if you input tomorrow)
return 0;
}else{
return TimeUnit.MILLISECONDS.toDays(diff)+1;
}
}
Same kind of code, but using the Joda-Time 2.3 library and Java 7.
DateTime dateTime = new DateTime( 2014, 2, 3, 7, 8, 9 );
DateTime twoDaysPrior = dateTime.minusDays( 2 );
dateTime: 2014-02-03T07:08:09.000-08:00
twoDaysPrior: 2014-02-01T07:08:09.000-08:00
I want to select records that have a created date between the first and the last day of a given month. I calculate the month with begin and enddate the following way:
The Date "month" is just a random date inside the timeframe
Calendar cal = Calendar.getInstance();
cal.setTime(month);
int endday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
int actualmonth = cal.get(Calendar.MONTH) + 1;
int year = cal.get(Calendar.YEAR);
Date begin = format.parse("01." + actualmonth + "." + year);
Date end = format.parse(endday + "." + actualmonth + "." + year);
When I think about this, I'd actually have to set the daytime as well, to avoid records going missing on the last day of the month.
I feel this is kinda inelegant, anyone up for a better solution?
What I would do is create a Calendar and set the month and year to the month you want, the day to 1, hour, minute and millisecond to zero. Then take the date of that for your begin range. Then I'd add a month, and then subtract a millisecond. Take the date of that for your end range.
Calendar dateCal = Calendar.getInstance();
dateCal.set(Calendar.MONTH, month);
dateCal.set(Calendar.YEAR, year);
dateCal.set(Calendar.HOUR_OF_DAY, 0);
dateCal.set(Calendar.MINUTE, 0);
dateCal.set(Calendar.SECOND, 0);
dateCal.set(Calendar.MILLISECOND, 0);
Date startDate = dateCal.getTime();
dateCal.add(Calendar.MONTH, 1)
dateCal.add(Calendar.MILLISECOND, -1);
Date endDate = dateCal.getTime();
There are methods available in the Calendar class for getting the first and last days of the month:
getActualMaximum(Calendar.DAY_OF_MONTH)
getActualMinimum(Calendar.DAY_OF_MONTH)
okay, solved it by Paul's example:
Calendar cal = Calendar.getInstance();
cal.setTime(month);
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.getActualMinimum(Calendar.DATE), 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
Date begin = cal.getTime();
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.MILLISECOND, -1);
Date end = cal.getTime();
thanks everyone