In my app I´m saving when I last updated some data from my server.
Therefore I used:
long time = Calendar.getInstance().getTimeInMillis();
Now I want that the data is updated twice a year at 03.03 and 08.08.
How can I check wheater one of these two date boarders were crossed since last update?
Change them to time in mseconds and compare:
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 3);
long time2= c.getTimeInMillis();
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 8);
long time3= c.getTimeInMillis();
if(time>time2){
//Logic
if(time>time3){
//Logic
}
}
There is something very important which took me a while to figure it out and can be very helpful to people out there, if you are looking for an answer to any of the following questions this is for you:
Why is my date not showing correctly?
Why even when I set the time manually it is not showing right?
Why is the month and the year showing one day less than the one that I set?
For some reason Java sorts the months values like an array, what I mean is that for Java January is 0 and DECEMBER is 11. Same happens for the year, if you set December as month 12 and year as 2012, and then try to do a "system.out.println" of the month and the year, it will show my month as January and the year as 2013!!
so what should you do?
Calendar cal = new GregorianCalendar();
cal.set(2012, 11, 26); // the date I want to input is 26/12/2012 (for Java, 11 is December!)
NOW WHAT IS THE CORRECT WAY TO GET THAT DATE TO SEE IT ON THE SCREEN?
if you try to "system.out.println of yourCalendar.DATE, yourCalendar.MONTH and yourCalendar.YEAR," THAT WILL NOT SHOW YOU THE RIGHT DATE!!!!
If you want to display the dates you need to do the following:
System.out.println (calact.get (calact.DATE));
// displays day
System.out.println (calact.get (calact.MONTH)+1);
//add 1 remember it saves values from 0-11
System.out.println (calact.get (calact.YEAR));
// displays year
NOW IF YOU ARE HANDLING STRINGS THAT REPRESENT DATES, OR....
IF YOU NEED TO COMPARE DATES BETWEEN RANGES , LET'S SAY YOU NEED TO KNOW IF DATE "A" WILL TAKE PLACE WITHIN THE NEXT 10 DAYS....THIS....IS.....FOR....YOU!!
In my case I was working with a string that had format "15/07/2012", I needed to know if that date would take place within the next 10 days, therefore I had to do the following:
1 get that string date and transform it into a calendar ( StringTokenizer was used here )
this is very simple
StringTokenizer tokens=new StringTokenizer(myDateAsString, "/");
do nextToken and before returning the day, parse it as integer and return it.
Remember for month before returning substract 1.
I will post the code for the first you create the other two:
public int getMeD(String fecha){
int miDia = 0;
String tmd = "0";
StringTokenizer tokens=new StringTokenizer(fecha, "/");
tmd = tokens.nextToken();
miDia = Integer.parseInt(tmd);
return miDia;
}
2 THEN YOU CREATE THE CALENDAR
Calendar cal = new GregorianCalendar(); // calendar
String myDateAsString= "15/07/2012"; // my Date As String
int MYcald = getMeD(myDateAsString); // returns integer
int MYcalm = getMeM(myDateAsString); // returns integer
int MYcaly = getMeY(myDateAsString); // returns integer
cal.set(MYcaly, MYcalm, MYcald);
3 get my current date (TODAY)
Calendar curr = new GregorianCalendar(); // current cal
calact.setTimeInMillis(System.currentTimeMillis());
4 create temporal calendar to go into the future 10 days
Calendar caltemp = new GregorianCalendar(); // temp cal
caltemp.setTimeInMillis(System.currentTimeMillis());
caltemp.add(calact.DAY_OF_MONTH, 10); // we move into the future
5 compare among all 3 calendars
here basically you ask if the date that I was given is for sure taking place in the future AND (&&) IF the given date is also less than the future date which had 10 days more, then please show me "EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!" OTHERWISE SHOW ME:
"EVENT WILL NOT TAKE PLACE WITHIN THE NEXT 10 DAYS".
if((cal.getTimeInMillis() > curr.getTimeInMillis()) && (cal.getTimeInMillis()< curr.getTimeInMillis()))
{ System.out.println ("EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!");}
else
{ System.out.println ("EVENT WILL *NOT* TAKE PLACE WITHIN THE NEXT 10 DAYS");}
ALRIGHT GUYS AND GIRLS I HOPE THAT HELPS. A BIG HUG FOR YOU ALL AND GOOD LUCK WITH YOUR PROJECTS!
PEACE.
YOAV.
If the comparison should involve only the year, month and day then you can use this method for check if c1 is before c2. Ugly, but works.
public static boolean before(Calendar c1, Calendar c2){
int c1Year = c1.get(Calendar.YEAR);
int c1Month = c1.get(Calendar.MONTH);
int c1Day = c1.get(Calendar.DAY_OF_MONTH);
int c2Year = c2.get(Calendar.YEAR);
int c2Month = c2.get(Calendar.MONTH);
int c2Day = c2.get(Calendar.DAY_OF_MONTH);
if(c1Year<c2Year){
return true;
}else if (c1Year>c2Year){
return false;
}else{
if(c1Month>c2Month){
return false;
}else if(c1Month<c2Month){
return true;
}else{
return c1Day<c2Day;
}
}
}
used compareTo method ..and this returns integer value .if returns -ve the days before in current date else return +ve the days after come current date
Related
I want to implement a tab layout with a range of months. This range should contain the last and next 12 Months.
I know how to get the next 12 months but i stuck at how to get the last AND next 12 months. I could use the joda time library but i think this lib is too big for my small android application.
Can anybody help my by providing a small code snipped? Thanks!
You can simply use a Calendar class instance to do it, with Calendar#add(int field,
int amount) like:
//getting month names
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
//here is what you need
Calendar c = Calendar.getInstance();
System.out.println(c.getTime().toString());
c.add(Calendar.MONTH, -12);
for (int i = -12; i <=12; i++){
c.add(Calendar.MONTH, +1);
System.out.println(months[c.get(Calendar.MONTH)]);
}
DateFormatSymbols is here used, to get the names of the months only.
You can use the calendar class to get the current month. Then u can subtract 1 to get the value of last month or add 1 to get next month.
Here is an example snippet.
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);
calendar.set(Calendar.MONTH, month - 1);
int lastMonth = calendar.get(Calendar.MONTH);
U could write a loop to calculate last and next 12 months this way.
Cheers :)
This question already has answers here:
Get the number of weeks between two Dates.
(19 answers)
Closed 8 years ago.
Let's see if you can help me. I want to get the number of weeks (starting on monday and finishing on sunday) between two dates, d1 and d2. Let's suppose that d2 is earlier of d1. That part of the code is already programmed and working. My problem now is that I'm not being able to code correctly the week program. This is what I made for now:
public static void getFullWeeks(Calendar d1, Calendar d2){
int Weeks = 0;
Calendar date2 = d2;
Calendar addWeek = GregorianCalendar.getInstance();
addWeek.setTime(date2.getTime());
addWeek.add(Calendar.DATE, 6);
while(addWeek.before(d1) || addWeek.equals(d1)){
if(date2.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
Weeks++;
}
date2.add(Calendar.DATE,1);
}
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ Weeks);
}
But the output is "0 weeks", so the program is not working. What's wrong? I'm not encountering the error and I'm not being capable to find a working solution for this problem.
Thank you!!
In Java 8 without external libraries you can do something like the following:
*Edited to account for week starting on Monday
// TechTrip - ASSUMPTION d1 is earlier than d2
// leave that for exercise
public static long getFullWeeks(Calendar d1, Calendar d2){
// In Java the week starts on Sunday from an integral perspective
// public final static int SUNDAY = 1;
// SEQUENTIAL UP TO
// public final static int SATURDAY = 7;
// make the starting date relative to the Monday we need to calculate from
int dayOfStartWeek = d1.get(Calendar.DAY_OF_WEEK);
// IF we have a partial week we should add an offset that moves the start
// date UP TO the next Monday to simulate a week starting on Monday
// eliminating partial weeks from the calculation
// NOTE THIS METHOD WILL RETURN NEGATIVES IF D1 < D2 after adjusting for
// offset
if (dayOfStartWeek == Calendar.SUNDAY) {
// add an offset of 1 day because this is a partial week
d1.add(Calendar.DAY_OF_WEEK, 1);
} else if (dayOfStartWeek != Calendar.MONDAY){
// add an offset for the partial week
// Hence subtract from 9 accounting for shift by 1
// and start at 1
// ex if WEDNESDAY we need to add 9-4 (WED Int Val) = 5 days
d1.add(Calendar.DAY_OF_WEEK, 9 - dayOfStartWeek);
}
Instant d1i = Instant.ofEpochMilli(d1.getTimeInMillis());
Instant d2i = Instant.ofEpochMilli(d2.getTimeInMillis());
LocalDateTime startDate = LocalDateTime.ofInstant(d1i, ZoneId.systemDefault());
LocalDateTime endDate = LocalDateTime.ofInstant(d2i, ZoneId.systemDefault());
return ChronoUnit.WEEKS.between(startDate, endDate);
}
Here's the main:
public static void main(String[] args) {
Calendar d1 = Calendar.getInstance();
Calendar d2 = Calendar.getInstance();
d2.add(Calendar.WEEK_OF_YEAR, 6);
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ getFullWeeks(d1, d2));
}
The output is as follows if the start date is a MONDAY:
The number of weeks (from monday to sunday) between both dates are: 6
Note, I did not assign date d2 to d1, making it the same reference. In that case you would get 0.
*The ChronoUnit takes a Temporal which is simply a date, time or offset. They must be of the same type. Temporals can be manipulated with plus and minus.
It seems to me there are couple of little mistakes you made:
1.) Your output is 0 weeks because elsewhere in your code you must have called this method with your first argument, d1, earlier than the second, while in the method body, you assume that d2 is earlier than d1. Such mistakes are easily avoided by using meaningful argument names. Appropriate argument names in this case are for example start and end.
2) If you execute this method using arguments in which d2 is earlier than d1, your method would fall into an infinite loop. It looks to me that adding to date2 does not change the date in addWeek.
3) Your method counts the number of weeks from Tuesday to Monday instead of Monday to Sunday. To fix this, add seven days to addWeek instead of six, or change the while loop to check only if addWeek is before d1 and increment weeks on sunday.
Putting all this together, I believe this will give you what you're looking for:
public static void getFullWeeks(Calendar start, Calendar end)
{
System.out.println("The number of weeks (from monday to sunday) between both dates are: " + getNrWeeksBetween(start, end));
}
private static int getNrWeeksBetween(Calendar start, Calendar end)
{
int weeks = 0;
Calendar counter = new GregorianCalendar();
counter.setTime( start.getTime() );
counter.add(Calendar.DATE, 6);
while( counter.before(end) )
{
if(counter.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) weeks++;
counter.add(Calendar.DATE, 1);
}
return weeks;
}
Your algorithm's wrong; your while loop needs to compare the same Calendar object you're modifying, but you don't do that, so you either have an infinite loop or you exit immediately with a return value of 0, depending on whether addDate is before or after d1 (since neither one changes). Your code should be:
public static void getFullWeeks(Calendar d1, Calendar d2){
int Weeks = 0;
Calendar addWeek = GregorianCalendar.getInstance();
addWeek.setTime(d2.getTime());
addWeek.add(Calendar.DATE, 6);
while(addWeek.before(d1) || addWeek.equals(d1)){
if(addWeek.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
Weeks++;
}
addWeek.add(Calendar.DATE,1);
}
System.out.println(
"The number of weeks (from monday to sunday) between both dates are: "
+ Weeks);
}
This question already has answers here:
How can I determine if a date is between two dates in Java? [duplicate]
(11 answers)
Closed 9 years ago.
I'm trying to write a schedule program in Java and I need to figure out what time it is, and whether the current time is in between two set times. Figuring out the current time is pretty simple, but do you have any suggestions for figuring out whether it is between two times of day. For example, it is 9:33 AM on a Thursday. So I would need to figure out which scheduled section of the week that time corresponds to. How would I go about comparing the time to set periods during the week, for example an Array of sectioned times during a week such as {Monday from 9-10 AM, Tuesday from 3-4 PM, Thursday from 8-11 AM}, and seeing which section of time the current time falls between?
An efficient way to find which period any date lies within would be to have a class;
public class TimePeriod implements Comparable<TimePeriod>{
Date start;
Date end;
//Constructor, getters, setters
boolean isIn(Date date) {
return date.after(start) && date.before(end);
}
public int compareTo(TimePeriod other) {
return start.compareTo(other.start);
}
}
..and then create a sorted list of TimePeriod where you can perform a binary search.
edit:
This might make the binary search easier;
int check(Date date) {
if (isIn(date)) {
return 0;
} else if (start.after(date)) {
return -1;
} else if (end.before(date)) {
return 1;
} else {
throw new IllegalStateException("Time has gone badly wrong");
}
}
If you're using Date Class, you could do it like this
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
boolean isAvailable = (before.getTime() < toCheck.getTime()) && after.getTime() > toCheck.getTime();
EDITED
As suggested by Jonathan Drapeau you could also use compareTo.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm");
Date before = sdf.parse("07/05/2012 08:00");
Date after = sdf.parse("07/05/2012 08:30");
Date toCheck = sdf.parse("07/05/2012 08:15");
//is toCheck between the two?
if you want to include the "initial" and "final" date range
boolean isAvailable = before.compareTo(toCheck) >= 0 && after.compareTo(toCheck) <= 0
if you want to exclude the "initial" and "final" date range
boolean isAvailable = before.compareTo(toCheck) > 0 && after.compareTo(toCheck) < 0
You could use it too on Calendar class.
Anyway, i highly recommend you to use Calendar. It's a way precise class
you could check it like this:
Calendar cal1 = Calendar.getInstance(); // for example 12:00:00
Calendar cal2 = Calendar.getInstance(); // for exmaple 12:30:00
Calendar userTime = Calendar.getInstance(); // time to test: 12:15:00
if(user.after(cal1)&& user.before(cal2)){
//...
}
And to initialize and set times to Calendar, check this:
http://www.tutorialspoint.com/java/util/calendar_settime.htm
I would suggest using the Epoch time.
For a definition of Epoch time: http://en.wikipedia.org/wiki/Epoch_time
Basically, its a number of seconds after a specific date, i believe in 1989. If you translate the 3 times (the current time and the 2 times to compare to) in epoch time you can just use > < = etc.
For information on getting epoch time, Try here (has many languages): http://shafiqissani.wordpress.com/2010/09/30/how-to-get-the-current-epoch-time-unix-timestamp/
Unfortunately, my java is lacking or I'd give you some code :)
Edit:
Java epoch time code:
long epoch = System.currentTimeMillis()/1000;
Because my Java is bad and I don't have an interpreter where I am, I can only suggest using this site to help convert the other dates to epoch time: http://www.epochconverter.com/
There is before(Date) and after(Date) method in Date Class.
secondDate.before(firstDate)
If you use Calendar class, it has explicit before() and after() methods:
Calendar startDate = ...
Calendar endData = ...
isBetween = currentDate.after(startDate) && currentDate.before(endDate);
I need help to check following conditions related to date and time...
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String CurrentDate= dateFormat.format(cal.getTime());
String ModifiedDate = dateTime taken from date n time picker widget ;
i have to check :
current ModifiedDate is not less than 5 minutes of current time
How to check this conditon in Android / Java..........?
Why are you formatting the date?
It's much easier to work with data in a "natural" representation rather than in a string representation. It's not clear whether your modified date has to be taken as a string, but if it does, the first thing you should do is parse it. You can then compare that with the current date and time using:
// Check if the value is later than "now"
if (date.getTime() > System.currentTimeMillis())
or
// Check if the value is later than "now + 5 minutes"
if (date.getTime() > System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5))
It's not really clear what you mean by "current ModifiedDate is not less than 5 minutes of current time" - whether you mean that it's not less than 5 minutes after, or not less than 5 minutes earlier, or something like that - but you should be able to change the code above to handle your requirements.
If you do a lot of date/time manipulation, I'd strongly recommend the use of Joda Time, which is a much better date/time API than java.util.Date/Calendar.
To check whether the given time is before/after the current time ,
There is a Calendar instance in Android...to compare date time values.
Calendar current_time = Calendar.getInstance ();
current_time.add(Calendar.DAY_OF_YEAR, 0);
current_time.set(Calendar.HOUR_OF_DAY, hrs);
current_time.set(Calendar.MINUTE, mins );
current_time.set(Calendar.SECOND, 0);
Calendar given_time = Calendar.getInstance ();
given_time.add(Calendar.DAY_OF_YEAR, 0);
given_time.set(Calendar.HOUR_OF_DAY, hrs);
given_time.set(Calendar.MINUTE, mins );
given_time.set(Calendar.SECOND, 0);
current_time.getTime();
given_time.getTime();
boolean v = current_calendar.after(given_calendar);
// it will return true if current time is after given time
if(v){
return true;
}
public static boolean getTimeDiff(Date dateOne, Date dateTwo) {
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
int day = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
int min= (int) ( TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
if(day>1)
{
return false;
}
else if(min>5)
{
return false;
}
else
{
return true;
}
}
usage:
System.out.println(getTimeDiff(new Date("01/13/2012 12:05:00"),new Date("01/12/2012 13:00:00")));
I am doing some table testing in word, all of the JUnits are done but i am having trouble testing a method - as i am the tester in this project and not the coder i am struggling to understand what is actually correct or not
public GregorianCalendar calcDeparture(String date, String time) {
String[] calDate = new String[3];
String[] calTime = new String[2];
calDate[0] = (date.substring(0, 2)); //Dat
calDate[1] = date.substring(2, 5); //Month
calDate[2] = "20" + date.substring(5, 7); //Year
calTime = time.split(":");
//Adds the year, month and day and hour and minute from the above splited arrays
int year = Integer.parseInt(calDate[2]);
int month = monthToInt(calDate[1]);
int day = Integer.parseInt(calDate[0]);
int hour = Integer.parseInt(calTime[0]);
int minute = Integer.parseInt(calTime[1]);
GregorianCalendar newDeparture = new GregorianCalendar(year, month, day, hour, minute, 0);
return newDeparture;
}
This is the method I am testing. If i pass it the values of "01AUG07 "14:40" i get a gregorian calander back but i don't know if the values inside of it are correct so i can't tick the passed or failed box. What i get back in the BlueJ object inspector is a load of really long numbers :D
can i get some help please
thanks
I suggest to check all the relevant values of the calendar at the same time using a SimpleDateFormat() like so:
SimpleDateFormat f = new SimpleDateFormat ("yyyy-MM-dd HH:mm");
String s = f.format (calcDeparture(yourDate, yourTime));
assertEquals ("2007-08-01 14:40", s);
Now call your method with odd dates (like 31.12.2999, August 45th, February 29th 2001, etc) to see what you get and how you should handle errors.
BlueJ? Consider using an IDE, not an educational software
The method is terribly written - working with dates using a strictly-formatted String is wrong.
Calendar (which is the supertype of GregorianCalendar) has the get method, which you can use like:
Calendar calendar = calcDeparture(yourDate, yourTime);
int day = calendar.get(Calendar.DAY_OF_YEAR);
int moth = calendar.get(Calendar.MONTH); //this is 0 based;
and so on
Why can you just not use the standard getters to check the individual fields, along the lines of:
Calendar cal = calcDeparture("01AUG07", "14:40");
if (cal.get(Calendar.YEAR) != 2007) { ... }