check if a date is equal independently of the year - java

I use javaSE 1.6 and I need to compare two dates and check if they are the same. this check needs to be independent of the year.
for example, i need to identify if today is the B-day of someone, and I need this code to be reused in the coming years.
so I need to perform the check, not on the year, not even on the day-of-the-year (issue with Leap year) but I can only rely on the day-of-the-month and the month number itself.
my input data, the birthday day of the person, it is in the Java class "Date"
is there any method of javaSE 1.6 that could help me?
I checked classes "Date" and "Calendar", but so far I couldn't find any hint to solve my issue.

ThreeTen Backport
public static MonthDay toMonthDay(Date utilDate) {
Instant inst = DateTimeUtils.toInstant(utilDate);
ZonedDateTime dateTime = inst.atZone(ZoneId.systemDefault());
return MonthDay.from(dateTime);
}
The MonthDay class of java.time is what you need, it’s a date without year, or conversely, a month and a day-of-month. Birthdays and other days to remember are the prime example for its use.
Like this:
Date birthday = // ...
Date today = new Date();
if (toMonthDay(today).equals(toMonthDay(birthday))) {
System.out.println("It’s her birthday");
} else {
System.out.println("It’s not her birthday");
}
On Java 6 you need to use the ThreeTen-Backport, the backport of java.time to Java 6 and 7.
I am hesitatingly using ZoneId.systemDefault() to use the JVM’s time zone setting for the conversion. On one hand the Date would normally assume this time zone; on the other hand this is fragile because the setting can be changed at any time from other parts of your program or other programs running in the same JVM. If you know better, by all means give a time zone like for example ZoneId.of("America/Adak")
If using Java 8 or later and the built-in java.time, the conversion is a little bit simpler:
ZonedDateTime dateTime = utilDate.toInstant().atZone(ZoneId.systemDefault());
return MonthDay.from(dateTime);
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

I found the way to call the Month and date-of-month in class Calendar.
here is my solution, I didn't find any other example on this topic, so I'll paste, maybe could help someone in the future.
if you have a more stylish solution, please let me know.
I'll be glad to learn :)
// date of the B-day 31st December
int month = Calendar.DECEMBER;
int date = 31;
boolean status = false;
// Class Date already filled with the date we wanna check.
Date beginDate;
Calendar c = Calendar.getInstance();
c.setTime(beginDate);
int dayOfMonthToCompare = c.get(Calendar.DAY_OF_MONTH);
int monthToCompare = c.get(Calendar.MONTH);
//perform check on day and Month
if(dayOfMonthToCompare == date && monthToCompare == month){
status = true;
}

Related

How to convert local time to LDAP timestamp in Java

I want to get two timestamps in LDAP format one has to be the beginning of the day and other has to be end of the day. It can be done by using Java 8 (using Joda-Time) but is there a way out using lower version like java 7.
This is the closest solution I found online, but I do not know how to get the timestamp of start of the day and end of the day. Additionally I need to check for 15 days back (start of the day end of the day from current system time)
To convert a Win32 filetime string to Date, use:
long fileTime = (Long.parseLong(inputDateString) / 10000L) - + 11644473600000L;
Date inputDate = new Date(fileTime);
To convert a Date to Win32 filetime, use:
long fileTime = (inputDate.getTime() + 11644473600000L) * 10000L;
String outputDate = Long.toString(fileTime);
e.g. 131220409910000000 will be converted to 2016/10/27 14-23-11 and vice versa
Check this url for a nice online epoch/filetime converter:
http://www.epochconverter.com/ldap
java.time and ThreeTen Backport
Instant ldapEpoch = Instant.parse("1601-01-01T00:00:00Z");
ZoneId zone = ZoneId.of("America/Port-au-Prince");
LocalDate date = LocalDate.now(zone);
Instant startOfDay = date.atStartOfDay(zone).toInstant();
Duration sinceLdapEpoch = Duration.between(ldapEpoch, startOfDay);
assert sinceLdapEpoch.getNano() == 0 : sinceLdapEpoch;
long ldapTimestamp = sinceLdapEpoch.getSeconds() * 10_000_000;
System.out.println(ldapTimestamp);
Output is (tested on jdk1.7.0_67):
132114384000000000
The start of the day differs from time zone to time zone. I have used America/Port-au-Prince as an example, you need to make your own pick. Use ZoneOffset.UTC if that is what you require.
For the end of the day use date.plusDays(1) instead of date in the same calculation. That will give you the first moment of the following day. Can you have the last moment of the current day instead? No, and you shouldn’t want to either. There is no last moment of a day. A day is a half-open time interval from the first moment of the day inclusive to the first moment of the next day exclusive. The best and the correct way to do in programming is to handle it as such (you may of course cheat and subtract 1 from the result you get to obtain the last possible LDAP timestamp of the day, not recommended).
I am using java.time, the modern Java date and time API. We don’t want to use Date or Calendar or other of the poorly designed and long outdated date and time classes in Java. java.time is so much nicer to work with.
Question: is there a way out using lower version like java 7?
Yes, java.time works nicely on Java 7. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
You could try the following:
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(2016, 4, 22); //your date
long time1= c.getTimeInMillis();
c.set(1601, 0, 1);
long time2= c.getTimeInMillis();
long ldap = (time1- time2) * 10000;

Convert month and day number to day of year using CALENDAR

I have two numbers.
First would be the month number.
Second would be the day number.
I also know the year.
How can I take those two number, month and day and make it into a single number DAY_OF_YEAR?
I'm using Java 1.7 and the Calendar functions.
java.time through ThreeTen Backport
int year = 2019;
int monthNumber = 9;
int dayNumber = 28;
LocalDate date = LocalDate.of(year, monthNumber, dayNumber);
int dayOfYear = date.getDayOfYear();
System.out.println("Day of year is " + dayOfYear);
Output from this snippet is:
Day of year is 271
Tested on Java 1.7.0_79 using ThreeTen Backport 1.3.6 and importing org.threeten.bp.LocalDate.
Consider avoiding the Calendar class
Four lines of the currently accepted answer creating and setting the Calendar object are substituted by just one line here. It’s typical for code using Calendar to be so wordy, which we shouldn’t want. Also despite the name a Calendar object is more than a calendar date, it also carries with it a time of day, a time zone and more, so I do not consider it a good fit for the job at hand. The code using Calendar will give a different result if the default locale is Thai, which will surprise most. The Calendar class is poorly designed and long outdated.
Instead I am using LocalDate of java.time, the modern Java date and time API.
Question: Can I use java.time on Java 7?
I'm using Java 1.7 …
java.time works nicely on Java 7. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Just using calendar and assuming by number of month you mean the zero-indexed one where 0 means January, here is an example for May 13th 2019:
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.ENGLISH);
c.set(Calendar.YEAR, 2019);
c.set(Calendar.MONTH, 4);
c.set(Calendar.DAY_OF_MONTH, 13);
System.out.println(c.get(Calendar.DAY_OF_YEAR));
Edit: As Ole V.V.'s answer pointed out you get a Calendar object with the system's timezone if you call 'Calendar.getInstance()', so I changed it that way that you explicitly specify the timezone and Locale to be used. The latter is important if you e.g. want to get a date's week number where the rules differ in different regions of the world.
You can concat your parts into a String, and use a SimpleDateFormatter like:
int year = 2019;
int month = 1;
int day = 23;
String string = "" + year + "-" + month + "-" + day;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse(string);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
The example is for 2019 January 23.

Is it possible to get time difference from directly Calendar fields?

sorry if the title is confusing. Let me explain clearly. I need to play with days, months and years. In order to do this I use Calendar. Here is my code;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int dayStart=0,monthStart=0,yearStart=0,dayFinish=0,monthFinish=0,yearFinish=0;
Calendar cal = (Calendar) Calendar.getInstance();
cal.set(Calendar.MONTH,Calendar.MAY); //SET MONTH AS MAY
cal.set(Calendar.DATE,1);
cal.set(Calendar.YEAR,2018);
monthStart=(cal.getCalendar.MONTH)+1);
dayStart=cal.get(Calendar.DATE);
yearStart=cal.get(Calendar.YEAR);
System.out.println("STARTING DAY: "+dayStart+" STARTING MONTH: "+monthStart+" STARTING YEAR: "+yearStart);
cal.add(Calendar.MONTH,6); //ADD 6 MONTHS
monthFinish = (cal.get(Calendar.MONTH)+1);
dayFinish = (cal.get(Calendar.DATE));
yearFinish = (cal.get(Calendar.YEAR));
System.out.println("FINISHING DAY: "+dayFinish+" FINISHNG MONTH: "+monthFinish+" FINISHING YEAR: "+yearFinish);
//WHAT I WANT IS printing out the days between 2 dates: 184
}
First, I set the time: 1 5 2018, then I add 6 months and the time becomes 1 11 2018. I need to get day difference as 184 (If I set the month January, it should be 181) Is it possible to do it just converting the corresponding Calendar fields (date,month,year) to secs or milliseconds and subtract millisecond value of (1 5 2018) from the (1 11 2018) and convert back milliseconds to days? There are similar questions but I couldn't find the solution exactly in the way I want.
java.time
LocalDate start = LocalDate.of(2018, Month.MAY, 1);
LocalDate finish = start.plusMonths(6);
long daysBetween = ChronoUnit.DAYS.between(start, finish);
System.out.format("Days between %s and %s: %d%n", start, finish, daysBetween);
IMHO it’s clear and it’s brief. And the bonus, it works correctly. Output is:
Days between 2018-05-01 and 2018-11-01: 184
The Calendar class has design problems and is now long outdated. So I recommend using java.time, the modern Java date and time API, instead. There is a way to have a Calendar count days correctly, but it’s more complicated than you would expect, and there is no reason why you should want to bother. Calculating the days from the milliseconds (which is shown in several answers on Stack Overflow, not only the other answer to this question) will sometime give the correct result, sometimes not. The two issues are: (1) Due to summer time (DST) and other discontinuities a day may be 23, 24 or 25 hours or some number between or even outside this interval. If a day in the interval is shorter than 24 hours, converting from the milliseconds will yield 1 day too little. (2) A Calendar (despite its name) also holds time of day. In your code it will hold the same time of day before and after you add 6 months. In other cases the different time of day may cause you to get 1 day too few, or in rare cases 1 day too many.
Question: Can I use java.time on Android?
Yes, java.time works nicely on Android devices. It just requires at least Java 6.
In Java 8 and later and on new Android devices (from API level 26, I’m told) the new API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310, where the modern API was first described).
On (older) Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. Make sure you import the date and time classes from package org.threeten.bp and subpackages.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
ThreeTen Backport project
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Java Specification Request (JSR) 310.
You can try the something similar to this should work for you
import java.util.*;
import java.util.concurrent.TimeUnit;
public class Calendar1 {
public static void main(String args[])
{
Calendar startDate = Calendar.getInstance();
//Setting year, month and day
startDate.set(2018, 5, 1);
Calendar endDate = Calendar.getInstance();
endDate.set(2018, 11, 1);
long end = endDate.getTimeInMillis();
long start = startDate.getTimeInMillis();
System.out.println("Time difference in days " + TimeUnit.MILLISECONDS.toDays(Math.abs(end - start)));
}
}
Something this you can do. Change the year, Month and Date and set in the calendar.
Use java.time.temporal.ChronoUnit to get the difference.
The sample code is as below.
public void daysBetween() {
Calendar startOfMonth = Calendar.getInstance();
startOfMonth.set(Calendar.YEAR, 2018);
startOfMonth.set(Calendar.MONTH, 10);
startOfMonth.set(Calendar.DAY_OF_MONTH, 1);
Calendar endOfMonth = Calendar.getInstance();
endOfMonth.set(Calendar.YEAR, 2018);
endOfMonth.set(Calendar.MONTH, 10);
endOfMonth.set(Calendar.DAY_OF_MONTH, 30);
System.out.println(ChronoUnit.DAYS.between(startOfMonth.toInstant(),endOfMonth.toInstant()));
}

Get time from date and databse then compare these time in java

I have a date: actDate, and its time was extracted as string timeFromAct
Then I have a reference time from database: timeValue, this was converted to string as timeFromDB
DateFormat formatTime;
formatTime = new SimpleDateFormat("HH:mm:ss");
Date actDate = actinfo.getActDate();
String timeFromAct = formatDay.format(actDate);
String date= ListOfConstants.SOME_DATE_REF;
ResultTable[] timeValue = RTManager.getSomethingDecodeList(date);
String timeFromDB = Arrays.toString(timeValue);
I know converting the two as Strings won't let me compare the 2 times but
I would like to know how do I compare these time values in an if statement (similar to below comparison)?
if (timeFromAct is greater than or equal to timeFromDB){
*some codes*
}
Write like this ;
if (actDate.after(timeFromDb) || actDate.compareTo(timeFromDB)==0 ){
*some codes*
}
In detail
actDate.after(timeFromDb) provides greater than case.
actDate.compareTo(timeFromDB)==0 provides equality of actDate and
timeFormDb.
Or in String comparasion if both are same format ;
if(timeFromAct.compareTo(timeFromDB) > 0 || timeFromAct .equals(timeFromDB)){..}
or more simple
if(!(timeFromAct.compareTo(timeFromDB) < 0)){..}
String.compareTo works as
"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns 0
"b".compareTo("a"); // returns a positive number, here 1
LocalTime from java.time
Date actDate = actinfo.getActDate();
ResultTable[] timeValue = RTManager.getSomethingDecodeList(date);
LocalTime actualTime = actDate.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalTime();
if (timeValue.length == 1) {
LocalTime timeFromDB = LocalTime.parse(timeValue[0].toString());
if (! actualTime.isBefore(timeFromDB)) {
System.out.println("timeFromAct is greater than or equal to timeFromDB");
} else {
System.out.println("timeFromAct is less than timeFromDB");
}
} else {
System.out.println("Unexpected number of ResultTable entries: " + timeValue.length);
}
A LocalTime is a time of day without date and without time zone. I believe that this is exactly what you need.
I have assumed that getActDate invariably returns an old-fashoined Date object. It would be better if you can modify it to return an appropriate type from java.time, the modern Java date and time API.
In the conversion from Date to LocalTime in the above code you will need to get your time zone right, or you will get incorrect results. I have tentatively assumed the JVM time zone setting, notated as ZoneId.systemDefault(), since the SimpleDateFormat in your question used this; but this is fragile since the setting can be changed from another part of your program or another program running in the same JVM. Better if you can specify the correct time zone like for example ZoneId.of("Asia/Manila").
Do check your assumptions. RTManager.getSomethingDecodeList will surely return only 1 value like this: [23:32:45]. The check costs so little, and it will be expensive to track down the bug if some day a new programmer on your project modifies it to return an array of a different length. Do help by issuing a helpful error message in this case.
The date-time classes that you used — DateFormat, SimpleDateFormat and Date — are long outdated and poorly designed. The first two in particular are renowned for being troublesome. I see no reason why you should want to use any of those if you can avoid it.
unfortunately i cannot import java.time from where i'm doing the codes.
If you are using at least Java 6, you can use java.time.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Java, set date to 0/0/0

I have an object with some dates and I'd like to return them in the getter. The problem is that i need to do Date.toString(); because I have to print them, and when the date is null I get a NullPointerException.
I was thinking about returning the date 0/0/0 when the date is null, but I don't know how to set this value. Is there any way? Just like new Date(0) returns the 1970-01-01-00:00:00, is there anything similar to this but to return 0/0/0?
Thanks!
There is no Date 0/0/0, by definition, as there is no Day 0 and no Month 0. A day is a member of the set {1,..,28 or 30 or 31} and month is a member of the set {1,...12}. Hence, it is impossible - and it is good that it is impossible - to express 0/0/0 as Date Object.
The terrible Date and Calendar classes were supplanted years ago by the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Zero-date senseless
is there anything similar to this but to return 0/0/0?
No.
Trying to represent a null with a date of all zeros is the wrong way to go. There is no such thing as a date of all zeros (year, month, and day all being zero).
Instead, pick an arbitrary date to use as a special value. Document thoroughly your choice and its meaning.
Do not choose a date too distant in time. Many libraries and databases are limited in their range of values. You do not want your data to break there.
Generally I would suggest using the epoch of 1970-01-01T00:00:00Z, the first moment of 1970 in UTC (the Z means UTC, and is pronounced “Zulu”). This moment is used as the epoch reference for Unix, the legacy date-time classes bundled with Java, and the modern date-time classes built into Java 8 and later. So many programmers and sysadmins will recognize this moment as special. The java.time classes include a constant for your convenience: Instant.EPOCH.
Obviously my suggestion applies to common business-oriented apps interested in forward-looking near dates, with past history not reaching back to 1970. If that does not meet your needs, pick another arbitrary value, such as 1900-01-01.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Java uses the Gregorian Calendar which has no 0 year. Also, you have to keep in mind that there is now zero month either. Setting a month to '0' would result in getting January, as the months are based on 0-index. Zero day does not exist either.
Assuming that you are getting and returning "modern" dates (AD), you could set your "lower bound" date in BC era. So, when you get a null date you could return a BC date to differentiate it from your actual ones. Here's the code:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.ERA, GregorianCalendar.BC); //Set the BC era
cal.set(Calendar.YEAR, 1); //Set the year to 1 BC
cal.set(Calendar.MONTH, 0); //Set the month to January
cal.set(Calendar.DAY_OF_MONTH, 1); //Set the day to 1st
DateFormat df = new SimpleDateFormat("yyyy MMM d G"); //Format the date
String returnedDate = df.format(cal.getTime()); //Generate a String of it for other use
You could customize the code to your needs if you are also getting dates from BC era (maybe by setting an even older date).
EDIT: Of course you could use what the others have suggested, namely checking for null and returning a "0/0/0" String but this may cause further problems later on, when you will try to parse the aforementioned String. Also, due to the fact that by definition 0/0/0 is not a valid date in the Gregorian Calendar (see clarification), you should avoid using this "wildcard" String and set an actual date, as I detailed above.
CLARIFICATION: The Gregorian Calendar does not contain neither a 0 year nor a 0 month or 0 day by definition and not by implementation in Java (meaning it's not an intentional limitation, it's part of its concept).
Class: LocalDate
Package: Threetenabp
My solution was to create LocalDate constants using the EPOCH date as basis with LocalDate.ofEpochDay(). And instead of returning a null date (that does not exist) I return a LocalDate object according to the case evaluated. Then depending on what I get back the getBirthdate method in my domain I do something.
Definition of constants
public class LocalDateUtils {
public static final LocalDate EMPTY_FIELDS = createLocalDate(0);
public static final LocalDate EMPTY_FIELD_DAY_OF_MONTH = createLocalDate(1);
public static final LocalDate EMPTY_FIELD_MONTH = createLocalDate(2);
public static final LocalDate EMPTY_FIELD_YEAR = createLocalDate(3);
/**
* Purpose: Create a date with #param epochDay days added
* Observation: EPOCH (1970-01-01)
*/
private static LocalDate createLocalDate(long epochDay) {
return LocalDate.ofEpochDay(epochDay);
}
}
Implementation
/**
* Purpose: Describe a birthday or a constant indicating empty field (s).
* Observation: According to if the parameters are zeros.
*/
LocalDate getBirthdate(int year,
int month,
int dayOfMonth) {
if (dayOfMonth == 0 && month == 0 && year == 0)
return LocalDateUtils.EMPTY_FIELDS;
if (dayOfMonth == 0)
return LocalDateUtils.EMPTY_FIELD_DAY_OF_MONTH;
if (month == 0)
return LocalDateUtils.EMPTY_FIELD_MONTH;
if (year == 0)
return LocalDateUtils.EMPTY_FIELD_YEAR;
return LocalDate.of(year, month, dayOfMonth);
}
Usage
if (getBirthdate() == LocalDateUtils.EMPTY_FIELDS) {
}
if (getBirthdate() == LocalDateUtils.EMPTY_FIELD_DAY_OF_MONTH) {
}
if (getBirthdate() == LocalDateUtils.EMPTY_FIELD_MONTH) {
}
if (getBirthdate() == LocalDateUtils.EMPTY_FIELD_YEAR) {
}
Source
GL
This simple approach can get you what you need, as already mentioned in the comments to your question:
public String dateString(Date date) {
if (date != null)
return date.toString();
else
return "0/0/0";
}
or
String dateString;
try {
dateString = date.toString();
}
catch(NullPointerException e) {
dateString = "0/0/0";
}
Update: the second alternative is discouraged as suggested in the comments.

Categories