Android Calendar is not giving expected results - java

I am passing values to calendar instance, but don't know why it is not performing as expected. I want to add one day to a specific date and then use that date.
Log.v("data going to calendar==",
"year="+Integer.parseInt(fy)+
"month="+Integer.parseInt(fm)-1)+
"day="+Integer.parseInt(fd)+
"hh="+Integer.parseInt(fh)+
"mm="+Integer.parseInt(fmn));
c.set(
Integer.parseInt(fd),
Integer.parseInt(fm)-1,
Integer.parseInt(fy),
Integer.parseInt(fh),
Integer.parseInt(fmn));
c.add(Calendar.DAY_OF_MONTH,1);
Log.v("data coming from calendar==",
"year = " + c.get(Calendar.YEAR)+
"month ="+ c.get(Calendar.MONTH)+
"day ="+c.get(Calendar.DATE)+
"hh="+c.get(Calendar.HOUR)+
"mm="+c.get(Calendar.MINUTE));
output is:
data gng to calendar==year = 2013month =7day =29hh=12mm=0
data cmng from calendar==year = 35month =1day =4hh=0mm=0
i run that code by putting comment on code to add one day, but the results are still same except for day, it means adding one day is working perfectly --->
year = 35month =1day =3hh=0mm=0

You call the set() method with the wrong parameters. According to the documentation the order must be year, month, date as first three parameters and you call it with date, month, year as the first parameters.
If you change your code to
c.set(Integer.parseInt(fy),
Integer.parseInt(fm)-1,
Integer.parseInt(fd),
Integer.parseInt(fh),
Integer.parseInt(fmn));
it should work as intended.
The strange values are because it treats 2013 as the day which is approx. 6 years that are added to the date.

If you want to add a day - 24 hours - to a date, add it as milliseconds: 1 day = 24 * 60 * 60 * 1000 milliseconds.
Calendar c = Calendar.getInstance();
//Set calendar's fields here
long time = c.getTimeInMilliseconds();
long nextDay = time + 24 * 60 * 60 * 1000;
c.setTimeInMillis(nextDay);

Related

Remaining years, months, days using joda time (Android)

I am trying to obtaining remaining years, months, and days between two dates:
So I have used Joda Time to do so:
DateTime endDate = new DateTime(2018,12,25,0,0);
DateTime startDate = new DateTime();
Period period = new Period(startDate,endDate,PeriodType.yearMonthDay());
PeriodFormatter formatter = new PeriodFormatterBuilder().appendYears().appendSuffix(" Year ").
appendMonths().appendSuffix(" Month ").appendDays().appendSuffix(" Day ").appendHours()..toFormatter();
String time = formatter.print(period);
This gives me string time: 2 Year 4 Month 22 Day
However, I want integer values of each number of remaining years, months, days.
So, Instead of "2 Year 4 Month 22 Day", I want to set my variables:
int year = 2
int month = 4
int day = 22
Is there any way to obtain these values separately instead of obtaining one string? Thank you so much! :)
i had the same requirement once ,here is the code snippet
LocalDate d=LocalDate.of(yy,mm,dd);
LocalDate d2=LocalDate.of(yy, mm, dd);
Period p=Period.between(d, d2);
long day,month,year;
day=p.getDays();
month=p.getMonths();
year=p.getYears();
System.out.println(day+" : "+month+" : "+year);
Invoke the methods provided by the DateTime class and just subtract them. An example for years is below:
int year = (int) dateTime#year#getField() - (int) dateTime2#year#getField()
UNTESTED code!! I'll be looking into it later but the general idea is the same, get the field information then just subtract it to get a value

Compare Timestamp with another Timestamp object

I'm newer to Java. I'm using two Timestamp objects dateFrom and dateTo. I want to check whether the dateFrom is 45 days earlier than dateTo. I used this code fragment to compare this
if(dateFrom.compareTo(dateTo) < 45)
{
// do the action;
}
I'm confusing with the 45 given in the code. Can I expect the correct result. will it meets my result.
compareTo() returns a value of -1, 0 or 1, depending on the result.
What you want to do is
long result = dateTo.getTime() - (1000 * 60 * 60 * 24 * 45) - dateFrom.getTime();
if(result >= 0) {
System.out.println("dateFrom is 45 days or more before dateTo");
else {
System.out.println("dateFrom is less than 45 days before dateTo");
}
This is rather ugly though. Is there a specific reason you're not using a Calendar?
You have to think about it a bit logically. First of all you need to get to a timestamp which is 45 days before the dateTo date. Time has various units (seconds, minutes, hours, days) so just checking < 45 is meaningless in this case. The compareTo() method is just there for ordering to know if a timestamp is before or after the other.
You could first create a Calendar for the timestamps, and add() dateFrom by 45 days. Then you can use the before() method to check if dateFrom is before dateTo.
Use Joda Time or Calendar class(add 45 days to dateFrom, compare the result with dateTo).
Do like this
Date dateFrom ="your from date";
Calendar cal = GregorianCalendar.getInstance();
cal .setTime(dateFrom);
cal.add(Calendar.DAY_OF_MONTH, 45);
Date expireDate = cal.getTime();
Date dateTo = new Date();
if(dateTo.after(expireDate)){
}
Since Timestamp in Java is number of milliseconds from UNIX Epoch - change 45 days to number of milliseconds (45d=45*24h=45*24*3600s=45*24*3600*1000ms) so if:
(time_B + 45*24*3600*1000) >= time_A
it means that time_B is 45 days (or more) 'further' in time that time_A
Of course you can use JodaTime and other libs too.

How do I add time to a timestamp?

I need to add 14 minutes and 59 seconds to an unknown time in an array. How do I do this? This is what I have so far:
Date duration = df.parse("0000-00-00 00:14:59");
arrayOpportunity[2] = arrayOpportunity[2] + duration;
The time is not being changed. Thanks!
I have done my research. I cant paste the entire code I have. But mainly I didnt want to make you read it all. Just looking for a simple answer of how to add two timestamps.
If you are talking about a java.sql.Timestamp, it has a method called setTime. java.util.Date has a setTime method as well for that sort of thing.
You could something like this:
static final Long duration = ((14 * 60) + 59) * 1000;
oldTimestamp.setTime(oldTimestamp.getTime() + duration);
If you want to add time in millis then you can just add
(((14 * 60) + 59) * 1000) <-- Mili second value of 14 m and 59 sec
If you just want to add times, I suggest using Joda Time.
The class LocalTime lets you add durations like this:
LocalTime timeSum = time.plusMinutes(14).plusSeconds(59);
Just add the appropriate number of milliseconds using #getTime() and #setTime():
timeStamp.setTime(timeStamp.getTime() + (((14 * 60) + 59)* 1000));
arrayOpportunity[2] = arrayOpportunity[2] + 14*60*1000 + 59*1000;
The Date object you have may work, but it doesn't really represent 14 minutes and 59 seconds, it just represents a particular time in calendar (eg. 14 minutes 59 after the epoch start which is 1st January 1970 00:14:59).

How do I increment a java.sql.Timestamp by 14 days?

I have an app that takes a Timestamp as a boundary for the start date and end date of a sql selection, I want to populate a hashmap with weeks this year since the first monday of the year as the values and the week number as the keys. I'm finding it really hard to work with timestamps and I don't feel very good about adding 86,400,000 seconds to it to increment the day, as this doesn't account for the leap days, hours, seconds.
I plan on adding 13 days 23 hours, 59 minutes and 59 seconds to it so that I can lookup the start date in the map by the week as the key, then use the start date to get the end date.
So I'm looking to try to get something like this:
Week startDate endDate
1 2011-01-03 00:00:00 2011-01-16 23:59:59
2 2011-01-17 00:00:00 2011-01-30 23:59:59
With the first two columns in the Map and the last one being calculated after looking it up. How do I safely increment a java.sql.Timestamp?
java.sql.Timestamp ts = ...
Calendar cal = Calendar.getInstance();
cal.setTime(ts);
cal.add(Calendar.DAY_OF_WEEK, 14);
ts.setTime(cal.getTime().getTime()); // or
ts = new Timestamp(cal.getTime().getTime());
This will correctly cater for daylight-time transitions in your default Timezone. You can tell the Calendar class to use a different Timezone if need be.
It worth noting that 14 days is not always 14 * 24 * 3600 seconds. When you have daylight savings, this can be an hour shorter or longer. Historically it can be much more complex than that.
Instead I would suggest using JodaTime or the Calendar to perform the time zone dependant calculation.
Java 8
Timestamp old;
ZonedDateTime zonedDateTime = old.toInstant().atZone(ZoneId.of("UTC"));
Timestamp new = Timestamp.from(zonedDateTime.plus(14, ChronoUnit.DAYS).toInstant());
private Long dayToMiliseconds(int days){
Long result = Long.valueOf(days * 24 * 60 * 60 * 1000);
return result;
}
public Timestamp addDays(int days, Timestamp t1) throws Exception{
if(days < 0){
throw new Exception("Day in wrong format.");
}
Long miliseconds = dayToMiliseconds(days);
return new Timestamp(t1.getTime() + miliseconds);
}
Timestamp my14DaysAfter = Timestamp.valueOf(myTimestamp.toLocalDateTime().plusDays(14));

milliseconds until next 5th second

So I want to do some monitoring and I want it to be on every fifth minute, so for example if the application starts at 1:47 monitor everything until 1:50 and then reset. I currently have this working for hour but I need to cut it down to every fifth minute and I'm having a little trouble coming up with the math.
I get all of the current time information
Calendar currentCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long currentTimeInMillis = currentCalendar.getTimeInMillis();
int hr = currentCalendar.get(Calendar.HOUR_OF_DAY);
int min = currentCalendar.get(Calendar.MINUTE);
int sec = currentCalendar.get(Calendar.SECOND);
int millis = currentCalendar.get(Calendar.MILLISECOND);
Now I need to find the next fifth minute, for hour I have this which works.
millisUntilNextHour = currentTimeInMillis + ((60L - min) * SECONDS_IN_MINUTE * 1000L) + ((60 - sec) * 1000L) + (1000L - millis);
Can anybody think of a way similar to above to get the milliseconds to the closest fifth minute?
Every fifth minute is 5 minutes * 60 seconds/minute * 1000 millisecond/second = 300,000 milliseconds.
Try this then:
millisUntilNextHour = (min*60*1000 + sec*1000 + millis + 299999)/300000*300000 - (min*60*1000 + sec*1000 + millis)
The +299999)/300000*300000 rounds up to the nearest 300,000. Then you get the difference between that and the current millisecond to find out how many milliseconds you are away from it.
Using the same approach as described in the question:
Calendar currentCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
int min = currentCalendar.get(Calendar.MINUTE);
currentCalendar.set(Calendar.MINUTE, 5 * (min / 5 + 1));
currentCalendar.set(Calendar.SECOND, 0);
currentCalendar.set(Calendar.MILLISECOND, 0);
millisUntilNextHour = currentCalendar.getTimeInMillis();
Update:
Reverted to my initial variant. It works as a charm. Lenient calendar (currentCalendar is lenient) works perfectly as expected when setting as minutes value greater than 60. From javadoc:
/**
* With lenient interpretation, a date such as "February 942, 1996" will be
* treated as being equivalent to the 941st day after February 1, 1996.
* With strict (non-lenient) interpretation, such dates will cause an exception to be
* thrown. The default is lenient.
*/
Why not use Quartz, which can handle this sort of thing easily. For the above you could specify a cron-type expression.
It may seem a bit heavyweight for your initial requirements but it's scaleable so it'll handle any future requirements.
Add five minutes to the current time, then set the seconds and millis to zero.
Note that the important thing is to use the .add(field, amount) method, as it will roll correctly into the next hour, etc. (including daylight savings, etc).
Calendar currentCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// store off the milliseconds from the epoch
int startTime = currentCalendar.getTime().getTime();
currentCalendar.add(Calendar.MINUTE, 5);
currentCalendar.set(Calendar.SECOND, 0);
currentCalendar.set(Calendar.MILLISECOND, 0);
// calculate the milliseconds difference.
int difference = currentCalendar.getTime().getTime() - startTime;
System.out.println("The number of milliseconds till " + currentCalendar.getTime() + " is " + startTime);

Categories