I am getting the current time in epoch. How can I add 1 month in future?
Date date = new Date();
int epoch = date.getTime();
Datatype for epoch - integer($int64)
To be precise: I want to add 30 days from current time.
I am using a tool that allows Groovy and Java code to be embedded. I used Date class because I can easily import java.text.DateFormat; and import java.text.SimpleDateFormat;. The tool that I have doesn't support Instant.
Since Java 8, use java.time for time usage
As epoch seconds, adding 30 days:
Instant.now().plus(30, ChronoUnit.DAYS).getEpochSecond()
As epoch milliseconds, adding 30 days:
Instant.now().plus(30, ChronoUnit.DAYS).toEpochMilli()
You don’t want to use Date, use date time API.
Instant.now().plus(30, ChronoUnit.DAYS)
Here's how I'd do it:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 30);
long epoch = calendar.getTimeInMillis();
System.out.println(epoch);
Result:
1606785580218
This is milliseconds. You can divide by 1000 to get the version in seconds. NOTE: The seconds version will fit in an int whereas the milliseconds version requires a long. So it's OK to do this if you want the seconds version in an int:
long epoch = ...
int epochSeconds = (int)(epoch / 1000);
BTW, Unix time (Epoch time, POSIX time) is defined as the number of seconds since 1 January 1970 UTC. Some systems will return the value in milliseconds to provide more accuracy, but such a value is officially a fractional Epoch time multiplied by 1000.
So far all answers are wrong.
That's because what you want is impossible.
You're mixing entirely incompatible concepts. You're asking to add 1 entity that is devoid of timezone and political meaning ('epoch-millis', which explicitly means: No timezone info!) with a concept that cannot be nailed down as meaning anything particular unless you supply timezone and era.
You cannot add a month to an epoch milli. Not because java doesn't let you, or because it is hard to program. You can't do it for the same reason you cannot point at the corner in a circle. It's literally impossible, by definition.
'epoch millis' are a concept that is fundamentally about a moment in time. Things like 'when the sun flared up'. "When I clapped my hands together just now". This concept is best represented in java by an instance of java.time.Instant. It is also represented by a java.util.Date, which is funny, because this is nothing like a Date, and indeed, j.u.Date is an utterly stupid name, and the authors have belatedly realized this, which is why (almost) all of the methods it has are marked #Deprecated with a note describing that Date's very name is a total lie. j.u.Date does not represent dates.
A month, that's an entirely different can of worms. There's nothing solid about a month. It could be 28 days. 30 days. 31 days. 30 days and an extra second tossed in. It could be a month that doesn't even exist, or is only 11 days (when political areas switch timezones, you can get some really bizarre things happening).
So, how do you add 'a month' to any instant in time?
You can't. It's not possible. You'd have no idea what to add, because there is no way to figure out if it's 28 days, 29, 30, 31, let alone leap seconds and era weirdness (recently, samoa switched to the other side of the dateline, and as a consequence, their december was only 30 days. The famous 'october revolution' that introduced communism to russia happened in november, at least as far as the entire world (except the russians) were concerned, because only the russians were on the julian calendar where it was still october. As part of the whole 'communism will take over the world!' scheme one of the very first things they did was get on the gregorian same as the rest of the world, and as a consequence, this date does not exist, AT ALL, in russian history: 1 through 13 feb 1918. They just. . were skipped. One day you wake up in moscow, walk outside, ask somebody: Hey, what date is it (though probably in russian), and they say: Why, 31st of January, comrade. Next day you repeat that exercise and now it is February 19th. So, february 1918 in russia was 15 days long.
See why 'please add 1 month' is just not a thing that could possibly be done unless you tell me when and where? If you tell me 'in russia', then I still don't know if I add 15, or 31, or 30, or 29, or 28. If you tell me 'Februari, in 1918', well, in the rest of the world, februari was 28 days. Only in russia it was 15.
Now, adding 'a month' to some human-oriented date/time construct, such as 'well, right now, in amsterdam', ah, that works: "THIS month, the month it is right now, in amsterdam", that is a question that has an answer. But, 'epoch millis' is java-ese for: "An instant in time, devoid of any and all geographical information", and by missing geo info it is also impossible to know when that is relative to any timezone, and therefore, utterly impossible.
So, what CAN you do? Well, many things, but first you need to figure out what you want to do, and only then can somebody tell you how to do it:
I just want to add what feels like an average month, and end up with epoch-millis. Okay, then just add 2.629.800.000, which is a rough estimate (that's about 30.4375 days, which is roughly the average length of a month. I have no idea what possible purpose this would serve, but it's surely a better plan than adding 30 days, or 31 days, or 28 days.
I want to first translate this epoch-millis into a time as humans would say it (in turns of year, month, day, hour, minute, and second), and then just increment the month value by 1, and leave it at that, in e.g. a ZonedDateTime object. Okay, then first figure out which timezone you want, then turn your epoch-millis into a ZonedDateTime, and THEN we've arrived at a point where 'add a month to this please' even makes sense, so now we can do that: .plusMonths(1), voila.
Same as previous, but then convert that back to epoch millis. Okay, well, do the same thing, and call .toInstant() at the end, and toEpochMillis() on that.
Most other ideas boil down to: Your question makes no sense and cannot be answered.
NB: The above all use the java.time packages. All other options (java.util.Date and java.util.Calendar are broken and unwieldy; generally attempting to do this or any other date-related job in those APIs will either be impossible, will give wrong answers, or there is a way but it is hard to figure out how and the resulting code will be hard to maintain and hard to follow. Why would you voluntarily punch yourself in the face? Why would you voluntary use crap APIs? Don't do that.
Given an epoch time: eg (1513213212) I should get 1 since its 1 am right now UTC. How would I go about converting it into the hour of the day? Is it possible to do it just using math (division, mod)?
It would be close to impossible to do it by using maths only. (Leap year and all). It's better to use established APIs which will do all the hard work.
You can use following method to do this.
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(1513213212* 1000L);
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(cal.get(Calendar.HOUR));//12 hour clock
System.out.println(cal.get(Calendar.HOUR_OF_DAY));//24 hour clock
Use java.time, the modern Java date and time API also known as JSR-310:
LocalTime timeOfDay = Instant.ofEpochSecond(1513213212L)
.atOffset(ZoneOffset.UTC)
.toLocalTime();
System.out.println(timeOfDay);
int hourOfDay = timeOfDay.getHour();
System.out.println(hourOfDay);
This prints:
01:00:12
1
Even if you just wanted to do the math, I would still prefer to use standard library methods for it:
long epochSeconds = 1513213212L;
// convert the seconds to days and back to seconds to get the seconds in a whole number of days
long secondsInWholeDays = TimeUnit.DAYS.toSeconds(TimeUnit.SECONDS.toDays(epochSeconds));
long hourOfDay = TimeUnit.SECONDS.toHours(epochSeconds - secondsInWholeDays);
System.out.println(hourOfDay);
This too prints 1.
Your intention was “Given an epoch time: eg (1513213212) I should get 1 since it’s 1 AM right now UTC.” Which of the above code snippets in your opinion most clearly expresses this intention? This is what I would use for making my pick.
While MadProgrammer is surely correct in his/her comment that date and time arithmetic is complicated and that you should therefore leave it to the date and time API, I believe that this is one of the rare cases where not too complicated math gives the correct answer. It depends on it being safe to ignore the issue of leap seconds, and if going for the math solution, you should make sure to check this assumption. Personally I would not use it anyway.
Is there a way to get number of days in a month using time4j lib?
in android default calendar, we can get it so simple like below
Calendar calendar=Calendar.getInstance();
int numOfDaysInMonth=calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
I mean a standard way, not crazy ways like going to the first Day of next month then come back one day and get day of month.
so can we do that in time4j calendars like "PersianCalendar"
The answer of #محمد علی using the default maximum has a problem: It does not use any calendar context so the maximum in leap years cannot be determined for the last month ESFAND. But the old comment given by #Tunaki is already a good and simple answer:
PersianCalendar today = PersianCalendar.nowInSystemTime();
int lengthOfCurrentMonth = today.lengthOfMonth();
Alternatively, you can also use the element PersianCalendar.DAY_OF_MONTH but then you should determine the contextual maximum, not the default maximum:
PersianCalendar today = PersianCalendar.nowInSystemTime();
int lengthOfCurrentMonth = today.getMaximum(PersianCalendar.DAY_OF_MONTH);
Both expressions will yield the same results in all ways and are completely equivalent.
For standard months (FARVARDIN (1) until BAHMAN (11)) the results will agree with the default maximum. But the last month ESFAND has either 29 days in normal years or 30 days in leap years. Both methods presented here will take this into account (but not the default maximum method).
Using JodaTime library (although I am a bit flexible). I realized some of the inputs coming in are breaking Joda time because the days of the month are above 31 or below 1 (because of client-side code).
I am using the LocalDate object for calendar manipulation. Is there a library or method to easily sanitize the dates so the input doesn't start throwing exceptions?
Some Scala code I am using now: EDIT: Fixed code
val now = new LocalDate();
val workingDate = now.withYear(y).withMonthOfYear(m).withDayOfMonth(d).withDayOfWeek(DateTimeConstants.SUNDAY)
ymdStart = toTimestampAtStart( workingDate )
For clarification, the goal here is to convert the date to a proper date, so if a user submitted July 38, it would convert to August 7. There's an incoming URL structure causing a lot of this and it looks like /timeline/2012/07/30.
For reasons of pure exercise (I agree normalization seems to be bad practice) I'm now just purely curious if there are libraries that deal with such a problem.
Thanks!
Final Update:
Like the answer points out, normalization was a poor idea. I did a lot of re-factoring on the client side to fix the incoming variables. This is the code I ended up using:
ymdStart = new Timestamp( toTimestampAtStart( new LocalDate(y,m,d).withDayOfWeek(1) ).getTime - 86400000 )
ymdEnd = new Timestamp( ymdStart.getTime + 691200000 )
First of all, a LocalDate is immutable, so each chained with...() is creating a new date.
Second, it is a well-known antipattern to update pieces of a date one at a time. The end result will depend on the current value of the date, the order in which you update the pieces, and whether or not the implementation "normalizes" dates.
In other words NEVER update a date/time piecemeal.
Assume for a minute that the implementation "normalizes" (i.e. corrects for overflow) invalid dates. Given your code, if today's date was 31-Jan-2011 and you did
now.setMonth(FEBRUARY);
now.setDayOfMonth(12);
the result will be 12-March-2011. The first statement sets the date to 31-February, which gets normalized to 03-March, then the day gets set to 12. Ah, you say, you can just set the day-of-month first. But that doesn't work for different starting points (construction of which is left as an exercise).
And from your question I surmise that JodaTime throws exceptions rather than normalize, which is anothe reason for not doing it this way.
I insert some data into Sqlite database and check before insert if record for this day allready exists. To check this I have to see if number of days are >0. For example difference (in days) between 2011-8-6 and 2011-8-5 is 1. How to do this in Java?
EDIT:
As #RayToal mentioned this could be done in database, so I did on that way:
SELECT julianday('now') - julianday(Date(Date)) from VIDEO_HISTORY;
Only problem with this is that it gives me decimal number. For example: 3.3442346529103816
Now I have to decide inside Java if given number is 3 of 4 days.
It code is for app that searches youtube for some term and writes statistical data about daily views into database. User is able to schedule job for example every day in 20:00 o'clock. But then he could decide to reschedule this job in 10:00 o'clock, so program has to understood this like difference is one day. So it's obvious that I have to round to first bigger number. Is there some method for this or I have to write myself?
EDIT2: According to links provided by #Michael-O this is best solution (using JodaTime):
DateTime start = new DateTime(new GregorianCalendar(2011, 8, 4).getTime());
DateTime end = new DateTime(new GregorianCalendar(2011, 8, 8).getTime());
int numberOfDays = Days.daysBetween(start.toDateMidnight(), end.toDateMidnight()).getDays();
System.out.println(numberOfDays);
You may want to consult this tutorial. Moreover you should consider using Joda Time's Period and consult this answer on stackoverflow.
If you want the number of calendar days (a Period in java.time parlance), then use (in Java 8):
import java.time.temporal.ChronoUnit;
import java.time.LocalDate;
ChronoUnit.DAYS.between(LocalDate.parse(from.toString()),LocalDate.parse(to.toString())
(This avoids a subtle bug in Java 8's java.sql.Date API)
If you want a Duration in days (physically elapsed time in 24-hour units), then use Marcelo's approach.