Number of days between today and your birthday using LocalDate class? - java

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 );

Related

java.time get first day of selected month

I am trying to get day of week of first day in selected month. Main condition is use only java.time. I need smth like this:
DayOfWeek dayOfWeek = LocalDate.now().with(TemporalAdjusters.firstDayOfMonth()).getDayOfWeek();
I already have YearMonth, which i got by entering numbers of year and month. How can i get dayOfWeek of first day in month ? I did it like this:
DayOfWeek dayOfWeek = yearMonth.atDay(1).getDayOfWeek();
but i got a commentary, that i have "magic numbers" that i need eliminate by correct using library java.time.
Magic number
i got a commentary, that i have "magic numbers" that i need eliminate by correct using library java.time.
No, you did not use a magic number; that commentary is incorrect. The author of that commentary jumped too fast upon seeing a hard-coded literal number being passed as an argument. Indeed, passing a literal number as an argument is suspicious as a possible “magic number”, and worthy of a second look, but in this case is quite appropriate.
The term magic number refers to the use of numbers whose purpose/meaning/role is not immediately obvious. Passing 1 to YearMonth.atDay() is quite obvious, meaning the first of the month.
Personally I do wish the YearMonth class offered a atFirstOfMonth like it has atEndOfMonth. My motivation is to avoid this very problem: Being sensitive to spotting hard-coded literal number passed as argument. But no big deal. Your code’s call to atDay( 1 ) is correct and clear. Using a TemporalAdjuster is correct as well, but is not as obvious.
One-liner, if you like short code (I do not):
YearMonth.of( year , month ).atDay( 1 ).getDayOfWeek()
Some discussion follows to elucidate this topic.
YearMonth
I already have YearMonth, which i got by entering numbers of year and month.
Java offers a class for this, to represent an entire month: YearMonth.
YearMonth ym = YearMonth.now() ; // Capture the current year-month as seen through the wall-clock time used by the people of the JVM’s current default time zone.
I recommend passing objects of this class around your codebase rather than using mere integer numbers for year & month. Using objects provides type-safety, ensures valid values, and makes your code more self-documenting.
Time zone
Better to specify a time zone. For any given moment, the date varies around the globe by zone. Better to explicitly specify the desired/expected time zone than rely implicitly on the JVM’s current default which can change at any moment during runtime.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ; // Specify desired/expected time zone. Or explicitly ask for JVM’s current default: `ZoneId.systemDefault()`.
YearMonth ym = YearMonth.now( z ) ; // Capture the current year-month as seen through the wall-clock time used by the people of a particular region (time zone).
LocalDate
Get the date of the first day of month as a LocalDate.
LocalDate ld = ym.atDay( 1 ) ; // Get the first day of the month.
DayOfWeek
The DayOfWeek enum provides seven pre-existing objects, one for each day of the week. These are not mere strings, but are smart objects.
DayOfWeek dow = ld.getDayOfWeek() ;
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Generate a String representing the name of this day-of-week localized to the human language and cultural norms of a particular `Locale`.
Here is a solution by just passing an LocalDate object:
public static String getFirstWeekDay(LocalDate date) {
int day = 1;
int month = date.getMonthValue();
int year = date.getYear();
LocalDate newDate = LocalDate.of(year, month, day);
String dayOfWeek = newDate.getDayOfWeek().toString();
return dayOfWeek;
}
Alternatively, you could use the method below to get the DayOfWeek Enum:
public static DayOfWeek getFirstWeekDay(LocalDate date){
int day = 1;
int month = date.getMonthValue();
int year = date.getYear();
LocalDate newDate = LocalDate.of(year, month, day);
return newDate.getDayOfWeek();
}
I hope this helps.
If you have the month and the year and you just need the first day of the month I would do something like this:
DayOfWeek firstDay = LocalDate.of(year, month, 1).getDayOfWeek();
Basically, you build a date where the dayOfMonth param is 1.
Based on your solution for the first day of a month assuming yearMonth is a LocalDate this should work:
DayOfWeek dayOfWeek =yearMonth.with(TemporalAdjusters.firstDayOfMonth()).getDayOfWeek();
System.out.println(dayOfWeek);

How to retrieve minutes from string date?

I have stored date in a string. Now I want to get minutes from the date string. How can I convert it into minutes?
Here is how I stored in a class:
public String fromDate;
public String toDate;
I have set getter and setter methods. I have saved the date value now I want to retrive the value and convert to minutes.
Retriving Like this:
Calendar c = Calendar.getInstance();
String datefrom = eventData.getFromDate();
I tried using this calendar instance:
c.set(Calendar.HOUR, hour);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.DATE,day);
Date datefrom = c.getTime();
startTime = String.valueOf(datefrom);
int hour = c.get(Calendar.HOUR);
int totalMinutes = hour * 60;
But this I can get from Date object. I have stored date in String format. How can I convert this?
Use Joda-Time:
String fromDate;
String toDate;
DateTimeFormatter format = new DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime fromDT = format.parseDateTime(fromDate);
DateTime toDT = format.parseDateTime(toDate);
Duration duration = new Duration(fromDT, toDT);
int minutes = duration.getStandardMinutes();
To import in Android Studio, update your build.gradle file:
apply plugin: 'android'
dependencies {
compile 'joda-time:joda-time:2.4'
compile 'joda-time:joda-time:2.2'
}
To convert a String to Date in Java you would have to use the DateFormat like the sample below:
String string = "January 26, 2016";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
Date date = format.parse(string);
System.out.println(date); // Tue Jan 26 00:00:00 GMT 2016
then you can go ahead with your Calendar implementation.
Usually i'd suggest to parse the time with a SimpleDateFormat, but I think in this case (since the dates seem to have a defined form and there might be problems with the timezones) i'll suggest to retrieve the information yourself:
String date = "Wed Jan 27 07:25:29 GMT+05:30 2016";
String[] times = date.substring(11, 16).split(":");
int minutes = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
System.out.println(minutes);
The part date.substring(11, 16) extracts the hours and minutes part from the string ("07:25").
The part .split(":"); splits the string "07:25" into two strings: "07" and "25".
after that you just parse those numbers to integers with Integer.parseInt(...) and calculate the number of minutes!
To get the minutes from a String is possible to use a DateFormat to convert the string to a Date and after use your code.
Your Question is really two questions:
How to parse a String to get a date-time object
How to get number of minutes since start-of-day from a date-time object
The first one, parsing a String into a date-time, has been covered at least 1,845 times on Stack Overflow, so I will skip it. The second Question is addressed below.
Please try to make your questions more clear. And focus on a single topic as narrowly as possible, as that is the intention for Stack Overflow.
Minutes-Of-Day
What you seem to want is called “Minutes-Of-Day”, the number of minutes since the start of the day.
Be careful and thoughtful here as there are two different definitions for minutes-of-day. You can get the actual number of minutes for a specific day in a specific time zone. Or you can calculate for a generic 24-hour day. Because of Daylight Saving Time (DST) and other anomalies, a day is not necessarily 24 hours long. For example, in most of the United States the use of DST means a day may be 23, 24, or 25 hours long.
The Question’s code and other Answers ignore the crucial issue of time zone (a common mistake in date-time work). If you do not specify a time zone, your JVM’s current default time zone is silently applied. Not good… that default can change at any moment, even during runtime! Better to always specify the time zone you expect/desire.
Avoid Old Date-Time Classes
The old date-time classes bundled with the earliest versions of Java are notoriously troublesome. Avoid them. Instead use the java.time framework built into Java 8 and later (see Tutorial). If that technology is not available to you, use the Joda-Time library (which inspired java.time). Examples below are in java.time in Java 8 Update 66.
java.time
Let’s look at March 3rd, 2015. This day was the "Spring ahead" DST changeover day for most of the United States. The clock jumped from 2 AM to 3 AM. So 03:00:00.0 on this day meant two hours (120 minutes) actually elapsed since the start of the day. If we treat this as a generic 24-hour day, we would say three hours (180 minutes) elapsed. The java.time classes can calculate minutes-of-day in both definitions.
First we get 3 AM on that changeover day. We use one of the time zones which recognized DST.
ZoneId zoneId = ZoneId.of ( "America/Los_Angeles" );
ZonedDateTime zdt = ZonedDateTime.of ( 2015 , 3 , 8 , 3 , 0 , 0 , 0 , zoneId );
Generic 24-Hour Day
Next we get the minutes since start of day assuming a generic 24-hour day. The ChronoField enum provides many ways to access TemporalField values such as MINUTE_OF_DAY.
long minutesOfDayForGeneric24HourDay = zdt.get ( ChronoField.MINUTE_OF_DAY );
Actual Day
To get the actual number of minutes elapsed since the start of this particular day for this particular time zone in which DST was changing over, we must do a bit more work. We have to determine the first moment of the day from which we can calculate elapsed time. To get that first moment, we must go through the LocalDate class which is a date-only value without time-of-day nor time zone. On that LocalDate object we call atStartOfDay to adjust back into a date-time value (a ZonedDateTime). You might think you could skip this by assuming the day starts at 00:00:00.0 but that is not always true.
ZonedDateTime zdtStart = zdt.toLocalDate ().atStartOfDay ( zoneId );
Now calculate elapsed time. The Duration class represents a span of time as hours, minutes, and seconds. From that Duration we can ask the total number of minutes, converting hours to minutes.
Duration duration = Duration.between ( zdtStart , zdt );
long minutesOfDayForActualDay = duration.toMinutes ();
Dump to console. Note how the generic ChronoField approach says 180 minutes while the actual Duration approach yields 120 minutes.
System.out.println ( "zdt: " + zdt + " | minutesOfDayForGeneric24HourDay: " + minutesOfDayForGeneric24HourDay + " | duration: " + duration + " | minutesOfDayForActualDay: " + minutesOfDayForActualDay );
zdt: 2015-03-08T03:00-07:00[America/Los_Angeles] | minutesOfDayForGeneric24HourDay: 180 | duration: PT2H | minutesOfDayForActualDay: 120

Printing Time and Date in both Universal Time and Standard Time

Writing a Java application that takes user input into a Time and Date class, but I am not sure how to take this user input and convert it into Universal and Standard time... I have spent multiple hours surfing the web and stack overflow and have not been able to find a solution.
I have hours, minutes, seconds, year, month, day all in separate integer variables and need to display them in Universal and Standard time.
Thanks for taking a look...
There are two solutions:
first is place all of input in the string and parse it:
String dateStr = ""
//put your input in this string in some format/ example:
//dateSttr = year + "." + month + "." + day + " " + hour + ":" + minute;
//It is better to use StringBuilder
DateFormat inputFormat = new SimpleDateFormat("yyyy.MM.dd hh:mm");
//note that hh is 12h-format and HH is 24h-format
DateFormat outputFormat1 = new SimpleDateFormat("your_outputFormat");
DateFormat outputFormat2 = new SimpleDateFormat("your_another_outputFormat");
Date date = inputFormat.parse(dateStr);
String o1, o2;
o1 = outputFormat1.format(date);
o2 = outputFormat2.format(date);
//o1 and o2 is your result.
For the rules, how this formats is done, see javadoc
The second solution is to get a new date and set your parameters:
Calendar cln = Calendar.getInstance().clear();
//by default you get a calendar with current system time
//now set the fields. for example, day:
cln.set(Calendar.YEAR, 2015);
cln.set(Calendar.MONTH, Calendar.FEBRUARY);
cln.set(Calendar.DAY_OF_MONTH, 17);
cln.set(Calendar.HOUR_OF_DAY, 18);//Calendar.HOUR for 12h-format
cln.set(Calendar.MINUTE, 27);
See more about setting calendar in javadoc
Note, that in the second variant, you might have some fields undefiend.
If #JonSkeet 's assumption and mine is correct, you're starting with either UTC or your local time. Displaying it is just a matter of formatting your output.
For the other type of time, you add or subtract a number of hours, which you can find on the web. The tricky part is that this may push you into the next calendar day, or pull you back into the previous one. To deal with that, I figure you want to either
implement an adder for year, month, day, hour--or
convert those to decimal somethings (Excel uses days, for instance, where as I write this it's 42328.08813), shift the value by the appropriate number of hours, and convert it back.
java.time
The Answer by TEXHIK is correct, but outdated. Also, as others mentioned, I do not know what you mean by "Universal and Standard time". But I'll try to get you part way there.
As of Java 8, the old java.util.Date/.Calendar classes have been supplanted by the new java.time framework. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
The ZonedDateTime class has a factory method taking numbers for year, month, and so on.
Plus you must specify a time zone. If your numbers represent a date-time in UTC, use the ZoneOffset.UTC constant. For other time zones, specify a ZoneId object by using a proper time zone name; never use the 3-4 letter codes such as EST or IST as their are neither standardized nor unique.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
// ZoneId zoneId = ZoneOffset.UTC; // ZoneOffset is a subclass of ZoneId.
ZonedDateTime zdt = ZonedDateTime.of( 2015 , 1 , 2 , 3 , 4 , 5 , 6 , zoneId );
zdt: 2015-01-02T03:04:05.000000006-05:00[America/Montreal]
You can convert to UTC or another time zone.
ZonedDateTime zdt_Kolkata = zdt.withZoneSameInstant ( ZoneId.of("Asia/Kolkata") );
ZonedDateTime zdt_Utc = zdt.withZoneSameInstant ( ZoneOffset.UTC );
zdt_Kolkata: 2015-01-02T13:34:05.000000006+05:30[Asia/Kolkata]
zdt_Utc: 2015-01-02T08:04:05.000000006Z
If working with classes not yet updated for java.time, convert to a java.util.Date. First extract a Instant object, a moment on the timeline always in UTC.
java.util.Date date = java.util.Date.from ( zdt.toInstant () );

create/find java class with simple constructor (hour, min) for use extending GregorianCalendar

I want to store a user-specified rough time of day (unspecified date) in a Java object. Can I instantiate a LocalTime object and set its hours and minutes in one line of Java code? Or is there a different, more suitable existing class?
I have insufficient google wizardry to find such. Elaboration follows, and thank you:
< 1 year android/java exp.
I'm extending the GregorianCalendar class and coding a constructor for FutureCal that takes integer hour (0-23) and minute and returns a calendar-ish object with date/time matching the first future occurrence of that hour:minute (will be either today or tomorrow--for notification/reminder stuff). To allow for other constructors that might have two integers, I would like to use or create a TimeOfDay class/type (comprised of integers hour & minute) and use that instead as parameter to my constructor. Is this a) possible b) appropriate?
Thanks for your time.
Joda-Time
The Joda-Time library is a popular and well-worn replacement for the awful mess that is GregorianCalendar, java.util.Date, SimpleTextFormat, and such. Joda-Time works on Android.
LocalTime
Joda-Time offers a LocalTime to represent a time-only value without any date or time zone. This class has the constructor you want, passing hour and minute values.
java.time
The new java.time package built into Java 8 (inspired by Joda-Time) also offers a similar LocalTime class. But Java 8 technology is not available for Android.
Example Code
Here is some example code using Joda-Time 2.4.
LocalTime localTime = new LocalTime( 13, 15 ); // Quarter-hour after 1 PM.
You can apply that LocalTime to a DateTime object. So, Joda-Time already provides everything you are trying to invent. Here is some example code setting today’s date-time to the desired time-of-day unless that has already passed in which case we slide to tomorrow’s date and re-apply our desired time-of-day.
LocalTime localTime = new LocalTime( 13 , 15 ); // Quarter-hour after 1 PM.
System.out.println( "localTime: " + localTime );
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // Or DateTimeZone.UTC
DateTime today = localTime.toDateTimeToday( timeZone );
DateTime now = DateTime.now(); // You may want to pad an bit of extra time in case now is extremely close to midnight (new day).
if ( today.isBefore( now ) ) {
// If the local time in question when applied to today has already past, then
// adjust to tomorrow while accounting for Daylight Saving Time or other anomaly.
DateTime tomorrowInitial = today.plusDays( 1 ); // Get tomorrow by adding 1 day to today.
DateTime tomorrow = localTime.toDateTime( tomorrowInitial ); // DST or other anomaly may mean that tomorrow got adjusted to a different time-of-day. Override with our desired time-of-day.
System.out.println( "tomorrow: " + tomorrow );
// return tomorrow;
}
System.out.println( "today: " + today );
// return today;
When run.
localTime: 13:15:00.000
tomorrow: 2014-10-09T13:15:00.000-04:00
today: 2014-10-08T13:15:00.000-04:00
Best to avoid java.util.Date. But if required, you may convert from Joda-Time.
java.util.Date date = today.toDate(); // Convert from Joda-Time DateTime to java.util.Date.
Maybe I didn't understood all but why not use a Calendar? I mean, you can set the time in a Calendar object.
int hour = 'your hour';
int minute = 'your minute';
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, hour).
cal.set(Calendar.MINUTE, minute);
Can I instantiate a LocalTime object and set its hours and minutes in
one line of Java code?
Yes, provided that you are using Java 8 (LocalTime seems new in Java 8):
LocalTime time = LocalTime.of(hour, minute);
When you are wondering about the behavior of specific classes, it would behoove you to consult their documentation, in this case, http://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html. In most cases, you will get your answer faster, plus answers to followup questions.

SimpleDateformat and "Day of week in month" (F)

I would like to get which day of the week is the current day and looking the SimpleDateFormat class I tought that the "F" is what I need. So I wrote a little test:
System.out.println(new SimpleDateFormat("F").format(new Date()));
Today is wednesday and I expect to get 3 as output. Instead I get 2.
As english isn't my mothertongue, did I missunderstand the meaning of the format?
F - Day of week in month
E - Day name in week
try u - Day number of week (1 = Monday, ..., 7 = Sunday)
Note that 'u' is since Java 7, but if you need just day number of the week then use Calendar
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.DAY_OF_WEEK));
You can change first day of week by changing Locale or directly as
c.setFirstDayOfWeek(Calendar.SUNDAY);
Today is the second Wednesday in the current month.
The java.util.Calendar/.Date and related classes are a confusing mess as you have learned the hard way. Counting from zero for month numbers and day-of-week numbers is one of many poor design choices made in those old classes.
java.time
Those old classes have been supplanted in Java 8 and later by the java.time framework. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
DayOfWeek
For day of week, use the well-named DayOfWeek enum.
If you want an integer for day-of-week compliant with ISO 8601 where Monday = 1 and Sunday = 7, you can extract that from an instance of DayOfWeek.
Conversion
If starting with a java.util.Calendar object, convert to java.time.
An Instant is a moment on the timeline in UTC.
Instant instant = myJavaUtilCalendarObject.toInstant();
Apply a time zone in order to get a date in order to get a day-of-week.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
DayOfWeek dayOfWeek = zdt.getDayOfWeek();
Note that time zone in crucial in determining a date, and therefore a day-of-week. The date is not the same around the world simultaneously. A new day dawns earlier in Paris than in Montréal, for example.
Number Of Day-Of-Week
Now that we have java.time and this enum built into Java, I suggest you freely pass around those enum instances rather than a magic number.
But if you insist on an integer, ask the DayOfWeek.
int dayOfWeekNumber = dayOfWeek.getValue();
String Of Day-Of-Week
That enum generates a localized String for the name of the day-of-week.
String output = dayOfWeek.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ); // Or Locale.ENGLISH.
Indexes for the days of week start from 0, not 1.
F -> Day of week in month(1-5)
Today is - 09/01/2013(dd/MM/yyyy) which fall 2nd in week so it has printed 2.
If you try with 16/01/2013 then it would print 3.
F = Day of Week in Month
1day to 7day, it will print 1.
8day to 14day, it will print 2.
15day to 21day, it will print 3.
22day to 28day, it will print 4 and
29day to 31day, it will print 5.
just use this method for this.
public String day(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("EEEEEEEEE", new Locale("tr", "TR"));
return sdf.format(date);
}

Categories