I want to get today's day and a date which is one year after today. For example, if today is 2015-9-18, next year is 2016-9-18.
I would like to use Java LocalDate.
The current date is simply retrieved with:
LocalDate now = LocalDate.now();
Then, you can add one year to this date, using the method plusYears(years):
LocalDate oneYearAfter = now.plusYears(1);
LocalDate contains various methods to ease the task of adding or subtracting a temporal amount (like plusDays, plusMonths; the most general being plus(amount, unit) adding the amount given for the specified unit of time).
Related
So this sounds easy, just take the day and date in java and see if it's the same day using the system's time with the calendar. This I can do and this would be a question that's probably repeated multiple times on here.
But my question is how to get like Cyber Monday. Let's say I have a program and every year on Cyber Monday he needs to lower the prices in the shop by 70% or set the discount to 70%. (which is actually my goal) Should I use java calendar for it? Which I can I guess. But how should I do it? I can't just check for the day we are now is the same as 27-11-2017 because in 2018 it's not on 27-11-2018. So how should I calculate this or check for it?
Is it possible to use like a API which has annual events and where people can send a request to receive the date of the requested annual event? Like I noticed the google calendar API but this is only for calendars you made yourself. Which I'm not planning to add every annual event for my own.
I made this method, To check if it's CyberMonday, what it's main purpose is. At this moment I'm stuck doing it annually. How can I make this right for every year?
public static void CyberMonday() {
//Check here if it's Cybermonday or if it's day after cybermonday.
if(Server.getCalendar().getYMD().toString().equals("2017/11/27") ) {
Config.CYBER_MONDAY = true;
updateCyberMondayOnWebsite();
} else {
Config.CYBER_MONDAY = false;
}
}
You can use Java 8's new java.time API for that.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
You can use LocalDate class to get Thanksgiving for a specified year (assuming that it's in US, so it's the fourth Thursday of November), and then get the next Monday after it.
I also use the TemporalAdjusters class, which has built-in methods to get those dates. The code is:
// get Cyber Monday of a specified year
public LocalDate getCyberMonday(int year) {
// Thanksgiving: fourth Thursday of November
// get first day of November
LocalDate d = LocalDate.of(year, 11, 1)
// get the fourth Thursday
.with(TemporalAdjusters.dayOfWeekInMonth(4, DayOfWeek.THURSDAY));
// next monday after Thanksgiving
return d.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
}
With this you can get the Cyber Monday for any year:
// get Cyber Monday for year 2017
LocalDate cyberMonday = getCyberMonday(2017);
So you can compare with another dates:
// checking if today is Cyber Monday
boolean isCyberMonday = cyberMonday.equals(LocalDate.now());
If the date you want to check is a String, you must parse it first (with a DateTimeFormatter) and then compare it.
I'm doing in a generic way: parsing the String, getting the year from it and comparing with the Cyber Monday of that year.
In this example, the date is in the same format of your example (2017/11/27):
String input = "2017/11/27";
// parse the input (in year/month/day format)
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate parsedDate = LocalDate.parse(input, fmt);
// compare the parsed date with the Cyber Monday of the same year
LocalDate cyberMonday = getCyberMonday(parsedDate.getYear());
boolean isCyberMonday = cyberMonday.equals(parsedDate);
You must change the pattern to match your inputs. Check the DateTimeFormatter javadoc for more information about date patterns.
PS: LocalDate.now() will get the current date in the system's default timezone. If you want to guarantee it gets the current date in a specific timezone, you can do something like LocalDate.now(ZoneId.of("America/New_York")).
Note that I used America/New_York as the timezone: the API uses IANA timezones names (always in the format Region/City, like America/Sao_Paulo or Europe/Berlin).
Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().
I am working on a project and need to generate recurrences for a date range using iCal4J library.
Basically it is a simple RRule to repeat weekly, every friday for the duration of six months.
This is what I have:
Recur recur = new Recur("FREQ=WEEKLY;INTERVAL=1;BYDAY=FR;WKST=MO;UNTIL=20170428T003000Z;");
DateTime startDate = new DateTime("20160727T0030000Z");
Date endDate = recur.getUntil();
DateTime baseDate = new DateTime("20160727T003000Z");
DateList dateList = recur.getDates(baseDate, startDate, endDate, Value.DATE_TIME);
This generates weekly meetings every friday at half midnight, however the last meeting should be on the 27/01/2017 but instead it is 20/01/2017.
One meeting gets taken out.
Ps this only occurs within this date range (maybe something to do with Britsh Summer Time BST), however it is set to be UTC therefore it should not matter right?
Then if I change the UNTIL property from the recurrence rule to be 21-01-2017 at 23:59:59 then it gets picked up.
Any suggestions?
Regards
Try it out : Here is an example for my recurrence rule for same.
If my start date is 10/08/2016 and date is 10/12/2016 then this will
create recurring dates for all friday coming between these two dates.
Weekly Recurrence Rule is
RRULE:FREQ=WEEKLY;BYDAY=FR;INTERVAL=1;UNTIL=20161218T000000Z
RRULE:FREQ=WEEKLY;BYDAY=<Day of week>;INTERVAL=<Every month/with some interval>;UNTIL=<Until Date>
So as per this your rule will be like : "RRULE:FREQ=WEEKLY;BYDAY=FR;INTERVAL=1;UNTIL=20170428T003000Z"
I want to calculate the number of days between "today" and the user's birthday, which he/ she inputs. This is what the program should look like:
When are you born? 19961020 // the user inputs this
Today you are xxxx days old.
The date needs to be in this format: YYYYMMDD. And the program should also consider leap years. I have to use the LocalDate class:
LocalDate datum = LocalDate.now();
int år = datum.getYear();
int månad = datum.getMonthValue();
int dag = datum.getDayOfMonth();
Another thing I have to consider while coding is that I have to use my own code, and not other methods that are already made. Can you please help me with this? I have no clue where to start or how to proceed with my code.
Parse the strings.
Your input string happens to be in standard ISO 8601 format. The java.time classes use that standard as their default when parsing/generating textual representations of date-time values. So no need to specify your own formatting pattern; use a pre-defined format.
LocalDate birthDate = LocalDate.parse( "19961020" , DateTimeFormatter.BASIC_ISO_DATE );
Get today. Usually I recommend passing a ZoneId here for accuracy, but give or take a day does not really matter here in this scenario.
LocalDate today = LocalDate.now();
Ask for days between with the ChronoUnit class.
long days = ChronoUnit.DAYS.between( birthdate , today );
Period
You could use the Period class which represents a span of time as a number of years, months, and days.
Period period = Period.between( birthdate , today );
I'm trying to convert a java.time.LocalTime object to java.util.Date but can't find any suitable method. What's the correct way to do this?
Is there any reason why java doesn't seem to ship with a built-in direct conversion method?
To possible duplicates:
How to convert joda time - Doesn't work for me, probably I'm missing some "joda" libraries?
How to convert Date to LocalTime? - This adresses conversion the other way around.
LocalTime actually can't be converted to a Date, because it only contains the time part of DateTime. Like 11:00. But no day is known. You have to supply it manually:
LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);
Here's a blog post which explains all the conversions between the new and the old API.
There's no simple built-in conversion method, because these APIs approach the idea of date and time in completely different way.
LocalTime lt = ...;
Instant instant = lt.atDate(LocalDate.of(A_YEAR, A_MONTH, A_DAY)).
atZone(ZoneId.systemDefault()).toInstant();
Date time = Date.from(instant);
From :
http://blog.progs.be/542/date-to-java-time
I added the data (hour, minute, second) one by one (from localtime to date):
reta.setHours(vol.getRetard().getHour());
reta.setMinutes(vol.getRetard().getMinute());
reta.setSeconds(vol.getRetard().getSecond());
Note :
reta: Date veriabble ;
vol.getRetard (): localtime variable
As others have said, it’s a problematic question in that a LocalTime and a Date really represent quite different and almost unrelated concepts. A LocalTime is a time of day without time zone, such as 19:45 (or 7:45 PM). A Date is a point on the time line; if it happens to coincide with 19:45 on some date in some time zone, it will not in other time zones.
I believe that the conventional way of misusing (indeed) a Date for an hour of day is setting it to that time of day on January 1, 1970 in the default time zone of the JVM. This practice carries all of the liabilities already mentioned. In particular the JVM default time zone setting can be changed at any time from another part of your program or any other program running in the same JVM. This means that a completely unrelated program may suddenly cause your Date to indicate a different time of day than the one you had initialized it to.
There’s nothing better we can do, so here goes:
LocalTime time = LocalTime.of(11, 0);
Instant timeOnEpochDayInDefaultTimeZone = LocalDate.EPOCH
.atTime(time)
.atZone(ZoneId.systemDefault())
.toInstant();
Date oldfashionedDateObject = Date.from(timeOnEpochDayInDefaultTimeZone);
System.out.println(oldfashionedDateObject);
In my time zone output from this snippet is:
Thu Jan 01 11:00:00 CET 1970
Here is another approach:
We can add a LocalDate to the LocalTime in order to make it a LocalDateTime and then convert it to Date using the valueOf method of java.sql.Timestamp like this:
LocalTime localTime = LocalTime.now();
Date date = java.sql.Timestamp.valueOf(localTime.atDate(LocalDate.now()));
As #Dariusz said, we cannot convert LocalTime to Date directly as it contains only time part but Date must contain all the value along with the timeZone.
In order to get the date part, we can use LocalDate.now(). It will give us LocalDate object with today's date.
Now, we have both LocalDate and LocalTime, we can now use the LocalDateTime.of(date: LocalDate, time: LocalTime) or localTime.atDate(date: LocalDate) to get the LocalDateTime object.
And now we can convert the LocalDateTime to Date using below kotlin extension function.
fun LocalDateTime.toDate(): Date {
return Date.from(this.atZone(ZoneId.systemDefault()).toInstant())
}
I need to generate a new Date object for credit card expiration date, I only have a month and a year, how can I generate a Date based on those two? I need the easiest way possible. I was reading some other answers on here, but they all seem too sophisticated.
You could use java.util.Calendar:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.YEAR, year);
Date date = calendar.getTime();
java.time
Using java.time framework built into Java 8
import java.time.YearMonth;
int year = 2015;
int month = 12;
YearMonth.of(year,month); // 2015-12
from String
YearMonth.parse("2015-12"); // 2015-12
with custom DateTimeFormatter
import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM yyyy");
YearMonth.parse("12 2015", formatter); // 2015-12
Conversions
To convert YearMonth to more standard date representation which is LocalDate.
LocalDate startMonth = date.atDay(1); //2015-12-01
LocalDate endMonth = date.atEndOfMonth(); //2015-12-31
Possibly a non-answer since you asked for a java.util.Date, but it seems like a good opportunity to point out that most work with dates and times and calendars in Java should probably be done with the Joda-Time library, in which case
new LocalDate(year, month, 1)
comes to mind.
Joda-Time has a number of other nice things regarding days of the month. For example if you wanted to know the first day of the current month, you can write
LocalDate firstOfThisMonth = new LocalDate().withDayOfMonth(1);
In your comment you ask about passing a string to the java.util.Date constructor, for example:
new Date("2012-09-19")
This version of the constructor is deprecated, so don't use it. You should create a date formatter and call parse. This is good advice because you will probably have year and month as integer values, and will need to make a good string, properly padded and delimited and all that, which is incredibly hard to get right in all cases. For that reason use the date formatter which knows how to take care of all that stuff perfectly.
Other earlier answers showed how to do this.
Like
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM");
Date utilDate = formatter.parse(year + "/" + month);
Copied from Create a java.util.Date Object from a Year, Month, Day Forma
or maybe like
DateTime aDate = new DateTime(year, month, 1, 0, 0, 0);
Copied from What's the Right Way to Create a Date in Java?
The most common sense approach would be to use the Date("YYYY-MM-DD") constructor even though it is deprecated. This is the easiest way to create a date on the fly. Screw whoever decided to deprecate it. Long live Date("YYYY-MM-DD")!!!
Don’t use this answer. Use the answers by Przemek and Ray Toel. As Przemek says, prefer to use a YearMonth for representing year and month. As both say, if you must use a date, use LocalDate, it’s a date without time of day.
If you absolutely indispensably need an old-fashioned java.util.Date object for a legacy API that you cannot change, here’s one easy way to get one. It may not work as desired, it may not give you exactly the date that you need, it depends on your exact requirements.
YearMonth expiration = YearMonth.of(2021, 8); // or .of(2021, Month.AUGUST);
Date oldFashionedDateObject = Date.from(expiration
.atDay(1)
.atStartOfDay(ZoneId.systemDefault())
.toInstant());
System.out.println(oldFashionedDateObject);
On my computer this prints
Sun Aug 01 00:00:00 CEST 2021
What we got is the first of the month at midnight in my local time zone — more precisely, my JVM’s time zone setting. This is one good guess at what your legacy API expects, but it is also dangerous. The JVM’s time zone setting may be changed under our feet by other parts of the program or by other programs running in the same JVM. In other words, we cannot really be sure what we get.
The time zone issue gets even worse if the date is transmitted to a computer running a different time zone, like from client to server or vice versa, or to a database running its own time zone. There’s about 50 % risk that your Date will come through as a time in the previous month.
If you know the time zone required in the end, it will help to specify for example ZoneId.of("America/New_York") instead of the system default in the above snippet.
If your API is lenient and just needs some point within the correct month, you’ll be better off giving it the 2nd of the month UTC or the 3rd of the month in your own time zone. Here’s how to do the former:
Date oldFashionedDateObject = Date.from(expiration
.atDay(2)
.atStartOfDay(ZoneOffset.UTC)
.toInstant());