Get a Date instance for a day of week and time - java

I have a config file from where I am reading a day of week and a time of day in 24 hour format. A sample entry looks like this:
NextRun=Sunday|15:00:00
I will parse them out into day and time variables. However, I want to find the equivalent millisecond timestamp for the next Sunday 3:00pm.
So for example, if today is Sunday 4:00pm or Tuesday 1:00am it will be the next Sunday 3:00pm, but if it is Sunday 2:30pm now, the expected time will be 30 minutes from now.

Get a Calendar instance and set it with the parsed time and day. If it has passed, add a week.
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
c.set(Calendar.HOUR_OF_DAY, 15);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
if (c.getTimeInMillis() - Calendar.getInstance().getTimeInMillis() < 0)
c.add(Calendar.DAY_OF_YEAR, 7);
return c.getTimeInMillis();

Use GregorianCalendar which extends Calendar. try something like:
GregorianCalendar currentTime = new GregorianCalendar();
GregorianCalendar targetTime = new GregorianCalendar();
//Get Day and Time from config file
targetTime.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
//Add a week if the targetTime is from last Sunday
if (targetTime.before(currentTime))
{
targetTime.add(Calendar.DAY_OF_YEAR, 7);
}
System.out.println(currentTime.getTime().toString() + ", " + targetTime.getTime().toString());

Related

Set Calendar Date to Current Date

I have variable with value of timeInMills which is past 3 days ago, I wanted to reset the date of it to current date but the time should be still.
Calendar calNow = Calendar.getInstance();
Calendar calSets = (Calendar)calNow.clone();
calSets.setTimeInMillis(TIME_IN_MILL); //set datetime from timeInMillis
//Reset the date to current Date.
How to do that?
Like this, get the properties you want, before you change the instance:
Calendar calNow = Calendar.getInstance();
Calendar calSets = (Calendar)calNow.clone();
int hours = calNow.get(Calendar.HOUR_OF_DAY)
int minutes = calNow.get(Calendar.MINUTE)
calSets.setTimeInMillis(TIME_IN_MILL); //set datetime from timeInMillis
//Reset the date to current Date.
calSets.set(Calendar.SECOND, 0);
calSets.set(Calendar.MILLISECOND, 0);
calSets.set(Calendar.HOUR_OF_DAY, hours);
calSets.set(Calendar.MINUTE, minutes);
You can reset a Calendar by calling setTimeInMillis(System.currentTimeMillis()):
TimeZone.setDefault(TimeZone.getTimeZone("UTC")); // Just for testing
final long TIME_IN_MILL = 1563204600000L; // 2019-07-15 15:30 UTC
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(TIME_IN_MILL);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
cal.setTimeInMillis(System.currentTimeMillis()); // Reset
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(cal.getTime()));
The code prints 2019-07-18 15:30:00.000, which is todays date with the time of day from the TIME_IN_MILL value.
If you don't want to rely on System.currentTimeMillis(), just get the value from the Calendar object, first thing:
Calendar cal = Calendar.getInstance();
long now = cal.getTimeInMillis();
cal.setTimeInMillis(TIME_IN_MILL);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
cal.setTimeInMillis(now);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

how to get the elapsed time from the beginning of a month to now in android programmatically

I want to to get the elapsed time from the beginning of a month to now in android programmatically.
preferably using Calendar.getInstance().
For example today is 12/10/2018. so the duration in millisecs will be 12/01/2018 to 12/10/2018
To retrieve the beginning of the month:
val cal = Calendar.getInstance()
cal.set(Calendar.HOUR_OF_DAY, 0)
cal.clear(Calendar.MINUTE)
cal.clear(Calendar.SECOND)
cal.clear(Calendar.MILLISECOND)
cal.set(Calendar.DAY_OF_MONTH, 1)
Then to calculate elapsed in milliseconds:
val current = Calendar.getInstance()
val timePassedMilliseconds=current.timeInMillis-cal.timeInMillis
is your problem creating a new Calendar and populating it? you can create an empty one, and just populate with the fields that you are interested in.
Calendar now = Calendar.getInstance();
Calendar startOfMonth = new GregorianCalendar();
calendar.set(Calendar.DAY_OF_MONTH, 1); //first day of month
calendar.set(Calendar.MONTH, now.get(Calendar.MONTH));
calendar.set(Calendar.YEAR, now.get(Calendar.YEAR);
timeElapsed = now.getTimeInMillis() - startOfMonth.getTimeInMillis() ;
You can use calendar.set(year,month,1,0,0,0); to get the timestamp of the first day of the month.
Calendar calendar = Calendar.getInstance();
Date d = new Date(1544371200000L); //12/10/2018
calendar.setTime(d);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
calendar.set(year,month,1,0,0,0);
Date firstDayOfMonth = calendar.getTime();
long duration = d.getTime() - firstDayOfMonth.getTime();

how to get next month date from specified date in Android

I'm designing a program where in my recylerview i wanted to display a list of items whose date is 4 days less or more than current date.
This will work for month:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
This will work for -4 day:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -4);

Date text box should be always 1st date current month.?

I want a javascript or java program should always give date 1st of current month.
Is there any tech?
You can use Calendar for Java
Date date = new Date(System.currentTimeMillis());
cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
Now you do what every you want to do with this Calendar object like to get the Day of the Week (Sat, Sun, .... )
int weekday = cal.get(Calendar.DAY_OF_WEEK);
And for JavaScript you can use:
var theFirst = new Date();
theFirst.setDate(1);
setDate sets the day of the month for the Date object (from 1 to 31). Then you can do whatever you want with theFirst, like get the day of the week.
Calendar ans = Calendar.getInstance();
ans.set(ans.get(Calendar.YEAR),
ans.get(Calendar.MONTH),
1,
0,
0,
0
);
System.out.println(ans.getTime());

Java - How to calculate the first and last day of each week

I'm trying to create a weekly calendar that looks like this: http://dhtmlx.com/docs/products/dhtmlxScheduler/sample_basic.html
How can I calculate every week date? For example, this week is:
Monday - Sunday
7 June, 8 June, 9 June, 10 June, 11 June, 12 June, 13 June
I guess this does what you want:
// Get calendar set to current date and time
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 7; i++) {
System.out.println(df.format(c.getTime()));
c.add(Calendar.DATE, 1);
}
With the new date and time API in Java 8 you would do:
LocalDate now = LocalDate.now();
// determine country (Locale) specific first day of current week
DayOfWeek firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek();
LocalDate startOfCurrentWeek = now.with(TemporalAdjusters.previousOrSame(firstDayOfWeek));
// determine last day of current week
DayOfWeek lastDayOfWeek = firstDayOfWeek.plus(6); // or minus(1)
LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(lastDayOfWeek));
// Print the dates of the current week
LocalDate printDate = startOfCurrentWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd/MM/yyyy");
for (int i=0; i < 7; i++) {
System.out.println(printDate.format(formatter));
printDate = printDate.plusDays(1);
}
Java.time
Using java.time library built into Java 8:
import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
LocalDate now = LocalDate.now(); # 2015-11-23
LocalDate first = now.with(previousOrSame(DayOfWeek.MONDAY)); # 2015-11-23
LocalDate last = now.with(nextOrSame(DayOfWeek.SUNDAY)); # 2015-11-29
You can iterate over DayOfWeek.values() to get all current week days
DayOfWeek.values(); # Array(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
for (DayOfWeek day: DayOfWeek.values()) {
System.out.print(first.with(nextOrSame(day)));
} # 2015-11-23, 2015-11-24, 2015-11-25, 2015-11-26, 2015-11-27, 2015-11-28, 2015-11-29
First day of this week.
Calendar c = Calendar.getInstance();
while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
c.add(Calendar.DATE, -1);
}
Simply setting the day of week does not seem to be reliable. Consider the following simple code:
Calendar calendar = Calendar.getInstance(Locale.GERMANY);
calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF%n", calendar);
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF%n", calendar);
System.out.printf("First day of week: %d%n", calendar.getFirstDayOfWeek());
The result of running this program is:
Starting day: 2011-09-18
Last monday: 2011-09-19
First day of week: 2
In other words, it stepped forward in time. For a German locale, this is really not the expected answer. Note that the calendar correctly uses Monday as first day of the week (only for computing the week of the year, perhaps).
You can build up on this: The following code prints the first and last dates of each week for 15 weeks from now.
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
for(int i=0; i<15; i++)
{
System.out.print("Start Date : " + c.getTime() + ", ");
c.add(Calendar.DAY_OF_WEEK, 6);
System.out.println("End Date : " + c.getTime());
c.add(Calendar.DAY_OF_WEEK, 1);
}
If you know which day it is (Friday) and the current date (June 11), you can calculate the other days in this week.
I recommend that you use Joda Time library. Gregorian Calendar class has weekOfWeekyear and dayOfWeek methods.
Calendar startCal = Calendar.getInstance();
startCal.setTimeInMillis(startDate);
Calendar endCal = Calendar.getInstance();
endCal.setTimeInMillis(endDate);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
while (startCal.before(endCal)) {
int weekNumber = startCal.get(Calendar.WEEK_OF_YEAR);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date sunday = cal.getTime();
Log.d("sunday", "" + sdf.format(sunday));
cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
Date saturday = cal.getTime();
Log.d("saturday", "" + sdf.format(saturday));
weekNumber = weekNumber + 1;
startCal.set(Calendar.WEEK_OF_YEAR, weekNumber);
}
Yes. Use Joda Time
http://joda-time.sourceforge.net/
The algorithm you're looking for (calculating the day of the week for any given date) is "Zeller's Congruence". Here's a Java implementation:
http://technojeeves.com/joomla/index.php/free/57-zellers-congruence

Categories