I find it curious that the most obvious way to create Date objects in Java has been deprecated and appears to have been "substituted" with a not so obvious to use lenient calendar.
How do you check that a date, given as a combination of day, month, and year, is a valid date?
For instance, 2008-02-31 (as in yyyy-mm-dd) would be an invalid date.
Key is df.setLenient(false);. This is more than enough for simple cases. If you are looking for a more robust (I doubt that) and/or alternate libraries like joda-time, then look at the answer by user "tardate"
final static String DATE_FORMAT = "dd-MM-yyyy";
public static boolean isDateValid(String date)
{
try {
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
df.setLenient(false);
df.parse(date);
return true;
} catch (ParseException e) {
return false;
}
}
As shown by #Maglob, the basic approach is to test the conversion from string to date using SimpleDateFormat.parse. That will catch invalid day/month combinations like 2008-02-31.
However, in practice that is rarely enough since SimpleDateFormat.parse is exceedingly liberal. There are two behaviours you might be concerned with:
Invalid characters in the date string
Surprisingly, 2008-02-2x will "pass" as a valid date with locale format = "yyyy-MM-dd" for example. Even when isLenient==false.
Years: 2, 3 or 4 digits?
You may also want to enforce 4-digit years rather than allowing the default SimpleDateFormat behaviour (which will interpret "12-02-31" differently depending on whether your format was "yyyy-MM-dd" or "yy-MM-dd")
A Strict Solution with the Standard Library
So a complete string to date test could look like this: a combination of regex match, and then a forced date conversion. The trick with the regex is to make it locale-friendly.
Date parseDate(String maybeDate, String format, boolean lenient) {
Date date = null;
// test date string matches format structure using regex
// - weed out illegal characters and enforce 4-digit year
// - create the regex based on the local format string
String reFormat = Pattern.compile("d+|M+").matcher(Matcher.quoteReplacement(format)).replaceAll("\\\\d{1,2}");
reFormat = Pattern.compile("y+").matcher(reFormat).replaceAll("\\\\d{4}");
if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {
// date string matches format structure,
// - now test it can be converted to a valid date
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance();
sdf.applyPattern(format);
sdf.setLenient(lenient);
try { date = sdf.parse(maybeDate); } catch (ParseException e) { }
}
return date;
}
// used like this:
Date date = parseDate( "21/5/2009", "d/M/yyyy", false);
Note that the regex assumes the format string contains only day, month, year, and separator characters. Aside from that, format can be in any locale format: "d/MM/yy", "yyyy-MM-dd", and so on. The format string for the current locale could be obtained like this:
Locale locale = Locale.getDefault();
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale );
String format = sdf.toPattern();
Joda Time - Better Alternative?
I've been hearing about joda time recently and thought I'd compare. Two points:
Seems better at being strict about invalid characters in the date string, unlike SimpleDateFormat
Can't see a way to enforce 4-digit years with it yet (but I guess you could create your own DateTimeFormatter for this purpose)
It's quite simple to use:
import org.joda.time.format.*;
import org.joda.time.DateTime;
org.joda.time.DateTime parseDate(String maybeDate, String format) {
org.joda.time.DateTime date = null;
try {
DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
date = fmt.parseDateTime(maybeDate);
} catch (Exception e) { }
return date;
}
tl;dr
Use the strict mode on java.time.DateTimeFormatter to parse a LocalDate. Trap for the DateTimeParseException.
LocalDate.parse( // Represent a date-only value, without time-of-day and without time zone.
"31/02/2000" , // Input string.
DateTimeFormatter // Define a formatting pattern to match your input string.
.ofPattern ( "dd/MM/uuuu" )
.withResolverStyle ( ResolverStyle.STRICT ) // Specify leniency in tolerating questionable inputs.
)
After parsing, you might check for reasonable value. For example, a birth date within last one hundred years.
birthDate.isAfter( LocalDate.now().minusYears( 100 ) )
Avoid legacy date-time classes
Avoid using the troublesome old date-time classes shipped with the earliest versions of Java. Now supplanted by the java.time classes.
LocalDate & DateTimeFormatter & ResolverStyle
The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "31/02/2000";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd/MM/uuuu" );
try {
LocalDate ld = LocalDate.parse ( input , f );
System.out.println ( "ld: " + ld );
} catch ( DateTimeParseException e ) {
System.out.println ( "ERROR: " + e );
}
The java.time.DateTimeFormatter class can be set to parse strings with any of three leniency modes defined in the ResolverStyle enum. We insert a line into the above code to try each of the modes.
f = f.withResolverStyle ( ResolverStyle.LENIENT );
The results:
ResolverStyle.LENIENTld: 2000-03-02
ResolverStyle.SMARTld: 2000-02-29
ResolverStyle.STRICTERROR: java.time.format.DateTimeParseException: Text '31/02/2000' could not be parsed: Invalid date 'FEBRUARY 31'
We can see that in ResolverStyle.LENIENT mode, the invalid date is moved forward an equivalent number of days. In ResolverStyle.SMART mode (the default), a logical decision is made to keep the date within the month and going with the last possible day of the month, Feb 29 in a leap year, as there is no 31st day in that month. The ResolverStyle.STRICT mode throws an exception complaining that there is no such date.
All three of these are reasonable depending on your business problem and policies. Sounds like in your case you want the strict mode to reject the invalid date rather than adjust it.
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.
You can use SimpleDateFormat
For example something like:
boolean isLegalDate(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
return sdf.parse(s, new ParsePosition(0)) != null;
}
The current way is to use the calendar class. It has the setLenient method that will validate the date and throw and exception if it is out of range as in your example.
Forgot to add:
If you get a calendar instance and set the time using your date, this is how you get the validation.
Calendar cal = Calendar.getInstance();
cal.setLenient(false);
cal.setTime(yourDate);
try {
cal.getTime();
}
catch (Exception e) {
System.out.println("Invalid date");
}
java.time
With the Date and Time API (java.time classes) built into Java 8 and later, you can use the LocalDate class.
public static boolean isDateValid(int year, int month, int day) {
try {
LocalDate.of(year, month, day);
} catch (DateTimeException e) {
return false;
}
return true;
}
Building on Aravind's answer to fix the problem pointed out by ceklock in his comment, I added a method to verify that the dateString doesn't contain any invalid character.
Here is how I do:
private boolean isDateCorrect(String dateString) {
try {
Date date = mDateFormatter.parse(dateString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return matchesOurDatePattern(dateString); //added my method
}
catch (ParseException e) {
return false;
}
}
/**
* This will check if the provided string matches our date format
* #param dateString
* #return true if the passed string matches format 2014-1-15 (YYYY-MM-dd)
*/
private boolean matchesDatePattern(String dateString) {
return dateString.matches("^\\d+\\-\\d+\\-\\d+");
}
An alternative strict solution using the standard library is to perform the following:
1) Create a strict SimpleDateFormat using your pattern
2) Attempt to parse the user entered value using the format object
3) If successful, reformat the Date resulting from (2) using the same date format (from (1))
4) Compare the reformatted date against the original, user-entered value. If they're equal then the value entered strictly matches your pattern.
This way, you don't need to create complex regular expressions - in my case I needed to support all of SimpleDateFormat's pattern syntax, rather than be limited to certain types like just days, months and years.
I suggest you to use org.apache.commons.validator.GenericValidator class from apache.
GenericValidator.isDate(String value, String datePattern, boolean strict);
Note: strict - Whether or not to have an exact match of the datePattern.
I think the simpliest is just to convert a string into a date object and convert it back to a string. The given date string is fine if both strings still match.
public boolean isDateValid(String dateString, String pattern)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
if (sdf.format(sdf.parse(dateString)).equals(dateString))
return true;
}
catch (ParseException pe) {}
return false;
}
Assuming that both of those are Strings (otherwise they'd already be valid Dates), here's one way:
package cruft;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateValidator
{
private static final DateFormat DEFAULT_FORMATTER;
static
{
DEFAULT_FORMATTER = new SimpleDateFormat("dd-MM-yyyy");
DEFAULT_FORMATTER.setLenient(false);
}
public static void main(String[] args)
{
for (String dateString : args)
{
try
{
System.out.println("arg: " + dateString + " date: " + convertDateString(dateString));
}
catch (ParseException e)
{
System.out.println("could not parse " + dateString);
}
}
}
public static Date convertDateString(String dateString) throws ParseException
{
return DEFAULT_FORMATTER.parse(dateString);
}
}
Here's the output I get:
java cruft.DateValidator 32-11-2010 31-02-2010 04-01-2011
could not parse 32-11-2010
could not parse 31-02-2010
arg: 04-01-2011 date: Tue Jan 04 00:00:00 EST 2011
Process finished with exit code 0
As you can see, it does handle both of your cases nicely.
This is working great for me. Approach suggested above by Ben.
private static boolean isDateValid(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
Date d = asDate(s);
if (sdf.format(d).equals(s)) {
return true;
} else {
return false;
}
} catch (ParseException e) {
return false;
}
}
looks like SimpleDateFormat is not checking the pattern strictly even after setLenient(false); method is applied on it, so i have used below method to validate if the date inputted is valid date or not as per supplied pattern.
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public boolean isValidFormat(String dateString, String pattern) {
boolean valid = true;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
try {
formatter.parse(dateString);
} catch (DateTimeParseException e) {
valid = false;
}
return valid;
}
Two comments on the use of SimpleDateFormat.
it should be declared as a static instance
if declared as static access should be synchronized as it is not thread safe
IME that is better that instantiating an instance for each parse of a date.
Above methods of date parsing are nice , i just added new check in existing methods that double check the converted date with original date using formater, so it works for almost each case as i verified. e.g. 02/29/2013 is invalid date.
Given function parse the date according to current acceptable date formats. It returns true if date is not parsed successfully.
public final boolean validateDateFormat(final String date) {
String[] formatStrings = {"MM/dd/yyyy"};
boolean isInvalidFormat = false;
Date dateObj;
for (String formatString : formatStrings) {
try {
SimpleDateFormat sdf = (SimpleDateFormat) DateFormat.getDateInstance();
sdf.applyPattern(formatString);
sdf.setLenient(false);
dateObj = sdf.parse(date);
System.out.println(dateObj);
if (date.equals(sdf.format(dateObj))) {
isInvalidFormat = false;
break;
}
} catch (ParseException e) {
isInvalidFormat = true;
}
}
return isInvalidFormat;
}
Here's what I did for Node environment using no external libraries:
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return zeroPad([yyyy, mm, dd].join('-'));
};
function zeroPad(date_string) {
var dt = date_string.split('-');
return dt[0] + '-' + (dt[1][1]?dt[1]:"0"+dt[1][0]) + '-' + (dt[2][1]?dt[2]:"0"+dt[2][0]);
}
function isDateCorrect(in_string) {
if (!matchesDatePattern) return false;
in_string = zeroPad(in_string);
try {
var idate = new Date(in_string);
var out_string = idate.yyyymmdd();
return in_string == out_string;
} catch(err) {
return false;
}
function matchesDatePattern(date_string) {
var dateFormat = /[0-9]+-[0-9]+-[0-9]+/;
return dateFormat.test(date_string);
}
}
And here is how to use it:
isDateCorrect('2014-02-23')
true
// to return valid days of month, according to month and year
int returnDaysofMonth(int month, int year) {
int daysInMonth;
boolean leapYear;
leapYear = checkLeap(year);
if (month == 4 || month == 6 || month == 9 || month == 11)
daysInMonth = 30;
else if (month == 2)
daysInMonth = (leapYear) ? 29 : 28;
else
daysInMonth = 31;
return daysInMonth;
}
// to check a year is leap or not
private boolean checkLeap(int year) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
}
Here is I would check the date format:
public static boolean checkFormat(String dateTimeString) {
return dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}") || dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}")
|| dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}") || dateTimeString
.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z") ||
dateTimeString.matches("^\\d{4}-\\d{2}-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}Z");
}
public static String detectDateFormat(String inputDate, String requiredFormat) {
String tempDate = inputDate.replace("/", "").replace("-", "").replace(" ", "");
String dateFormat;
if (tempDate.matches("([0-12]{2})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMddyyyy";
} else if (tempDate.matches("([0-31]{2})([0-12]{2})([0-9]{4})")) {
dateFormat = "ddMMyyyy";
} else if (tempDate.matches("([0-9]{4})([0-12]{2})([0-31]{2})")) {
dateFormat = "yyyyMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([0-12]{2})")) {
dateFormat = "yyyyddMM";
} else if (tempDate.matches("([0-31]{2})([a-z]{3})([0-9]{4})")) {
dateFormat = "ddMMMyyyy";
} else if (tempDate.matches("([a-z]{3})([0-31]{2})([0-9]{4})")) {
dateFormat = "MMMddyyyy";
} else if (tempDate.matches("([0-9]{4})([a-z]{3})([0-31]{2})")) {
dateFormat = "yyyyMMMdd";
} else if (tempDate.matches("([0-9]{4})([0-31]{2})([a-z]{3})")) {
dateFormat = "yyyyddMMM";
} else {
return "Pattern Not Added";
//add your required regex
}
try {
String formattedDate = new SimpleDateFormat(requiredFormat, Locale.ENGLISH).format(new SimpleDateFormat(dateFormat).parse(tempDate));
return formattedDate;
} catch (Exception e) {
//
return "";
}
}
setLenient to false if you like a strict validation
public boolean isThisDateValid(String dateToValidate, String dateFromat){
if(dateToValidate == null){
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFromat);
sdf.setLenient(false);
try {
//if not valid, it will throw ParseException
Date date = sdf.parse(dateToValidate);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
return false;
}
return true;
}
With 'legacy' date format, we can format the result and compare it back to the source.
public boolean isValidFormat(String source, String pattern) {
SimpleDateFormat sd = new SimpleDateFormat(pattern);
sd.setLenient(false);
try {
Date date = sd.parse(source);
return date != null && sd.format(date).equals(source);
} catch (Exception e) {
return false;
}
}
This execerpt says 'false' to source=01.01.04 with pattern '01.01.2004'
We can use the org.apache.commons.validator.GenericValidator's method directly without adding the whole library:
public static boolean isValidDate(String value, String datePattern, boolean strict) {
if (value == null
|| datePattern == null
|| datePattern.length() <= 0) {
return false;
}
SimpleDateFormat formatter = new SimpleDateFormat(datePattern, Locale.ENGLISH);
formatter.setLenient(false);
try {
formatter.parse(value);
} catch(ParseException e) {
return false;
}
if (strict && (datePattern.length() != value.length())) {
return false;
}
return true;
}
A simple and elegant way for Android developers (Java 8 not required):
// month value is 1-based. e.g., 1 for January.
public static boolean isDateValid(int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
try {
calendar.setLenient(false);
calendar.set(year, month-1, day);
calendar.getTime();
return true;
} catch (Exception e) {
return false;
}
}
Below code works with dd/MM/yyyy format and can be used to check NotNull,NotEmpty as well.
public static boolean validateJavaDate(String strDate) {
if (strDate != null && !strDate.isEmpty() && !strDate.equalsIgnoreCase(" ")) {
{
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
date.setLenient(false);
try {
Date javaDate = date.parse(strDate);
System.out.println(strDate + " Valid Date format");
}
catch (ParseException e) {
System.out.println(strDate + " Invalid Date format");
return false;
}
return true;
}
} else {
System.out.println(strDate + "----> Date is Null/Empty");
return false;
}
}
I'm trying to count the days between two dates but I can't get a right result.
I did the same that someone described to me.
My result should be an int or long. For this example I would expext 11 but 10 is also fine.
That's the code:
String startDate = "2018-03-25";
String endDate = "2018-04-05";
Date startDate1 = stringToDate(startDate);
Date endDate1 = stringToDate(endDate);
long ab = daysBetween(startDate1, endDate1);
String ab1 = String.valueOf(ab);
And that's the methods:
public static long daysBetween(Date startDate, Date endDate) {
Calendar sDate = getDatePart(startDate);
Calendar eDate = getDatePart(endDate);
long daysBetween = 0;
while (sDate.before(eDate)) {
sDate.add(Calendar.DAY_OF_MONTH, 1);
daysBetween++;
}
return daysBetween;
}
public Date stringToDate(String stringDatum) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(stringDatum);
return date;
}
catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static Calendar getDatePart(Date date){
Calendar cal = Calendar.getInstance(); // get calendar instance
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight
cal.set(Calendar.MINUTE, 0); // set minute in hour
cal.set(Calendar.SECOND, 0); // set second in minute
cal.set(Calendar.MILLISECOND, 0); // set millisecond in second
return cal; // return the date part
}
java.util.Date, Calendar and SimpleDateFormat are part of a terrible API. They make the job of date/time handling harder than it already is.
Make yourself a favor and use a decent date/time library: https://github.com/JakeWharton/ThreeTenABP - here's a nice tutorial on how to use it - How to use ThreeTenABP in Android Project
With this API, it's so easy to do what you want:
LocalDate startDate = LocalDate.parse("2018-03-25");
LocalDate endDate = LocalDate.parse("2018-04-05");
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate); // 11
I've chosen to use LocalDate based on your code: the inputs have only day, month and year, and you're setting the hour/minute/seconds to zero, so I understand that you don't care about the time of the day to calculate the difference - which makes LocalDate the best choice.
Date and Calendar represent a specific point in time, and Calendar also uses a timezone, so Daylight Saving changes might affect the results, depending on the device's default timezone. Using a LocalDate avoids this problem, because this class doesn't have a timezone.
But anyway, I've tested your code and also got 11 as result, so it's not clear what problems you're facing.
private static long daysBetween(Date date1, Date date2){
return (date2.getTime() - date1.getTime()) / (60*60*24*1000);
}
I am trying to parse date strings, my problem is that those strings can have different dateformats depends on if they talk about today, tomorrow or another day.
If they talk about today event the format is like this: 20:45
If they talk about tomorrow event the format is: tomorrow 20: 45
And if they talk about another day the format is: May 10 2016
So I would like to know if I can parse the three of them with the same DateFormat, if not what will be the best way.
DateFormat format = new SimpleDateFormat("EEEE d ' de' MMMM ' de' yyyy", locale);
You cant use the same SimpleDateFormat to parse all types, and wont be a good practice neither, not readable and more complex not adding any special value, i would try something like this:
private static final SimpleDateFormat formatHHMM = new SimpleDateFormat("hh:mm");
private static final SimpleDateFormat formatOther = new SimpleDateFormat("MMM dd yyyy");
private static String convertDate(Date curDate) {
if (isToday(curDate)) {
return formatHHMM.format(curDate);
}
else if (isTomorrow(curDate)) {
return "Tomorrow " + formatHHMM.format(curDate);
}
return formatOther.format(curDate);
}
private static boolean isToday(Date curDate) {
Date today = Calendar.getInstance().getTime();
return today.equals(curDate);
}
private static boolean isTomorrow(Date curDate) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 1);
Date tomorrow = calendar.getTime();
return tomorrow.equals(curDate);
}
//Check the code with this
public static void main( String[] args )
{
Date curDate = new Date();
System.out.println( convertDate(curDate));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 1);
Date tomorrow = calendar.getTime();
System.out.println( convertDate(tomorrow));
calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 15);
Date other = calendar.getTime();
System.out.println( convertDate(other));
}
I don't think it's possible to parse the 3 formats with the same formatter. Although it may be possible to parse the first two with only one formatter, the difference of meaning (today or tomorrow) would imply a different logic, which can't be obtained with a single formatter.
I suggest you to handle each case separately, trying one after another:
try {
return LocalDate
.now()
.atTime(LocalTime.parse(date));
} catch (DateTimeParseException e) {
try {
return LocalDate
.now()
.plusDays(1)
.atTime(LocalTime.parse(date, DateTimeFormatter.ofPattern("'tomorrow' HH:mm")));
} catch (DateTimeParseException e1) {
return LocalDate
.parse(date, DateTimeFormatter.ofPattern("MMMM dd yyyy", Locale.ENGLISH))
.atStartOfDay();
}
}
I'm not sure about the clarity of the control flow, though. If the the number of input formats grows, a refactor into something clearer may be required.
if (DateFormat.charAt(0).isDigit() && DateFormat.charAt(1).isDigit() && DateFormat.charAt(2).isLetterOrDigit()==false .... {
new String SimpleDateFormat= '15.03.2016';
else {
if (DateFormat.charAt(0).isLetter('t') && DateFormat.charAt(1).isLetter('o') && and so on
{ SimpleDateFormat='16.03.2016'
and you may change the condition on 1 by 1 character to match all your type of data formats
import java.text.DateFormat;
import java.util.Date;
public class DatePlus {
public static void main(String[] args) {
Date now = new Date();
//Date now1 = new Date();
Date now2 = new Date();
DateFormat currentDate = DateFormat.getDateInstance();
int count1=10;
int count2=15;
Date addedDate1 = addDays(now2, count1);
Date addedDate2 = addDays(addedDate1, count2);
System.out.println(currentDate.format(addedDate1));
System.out.println(currentDate.format(addedDate2));
}
public static Date addDays(Date d, int days) {
d.setTime(d.getTime() + days * 1000 * 60 * 60 * 24);
return d;
}
}
both the date addedDate1 and addedDate2 output statements are printing the same date though the expected output is different.
The problem is that you don't return a new Date instance but change the provided one. You always modify and print the same instance.
Change your function to
public static Date addDays(Date d, int days) {
return new Date(d.getTime() + days * 1000 * 60 * 60 * 24);
}
Instead of writing your own method you can use Calender class:
public static void main(String[] args)
{
Date now = new Date();
// Date now2 = new Date();
DateFormat currentDate = DateFormat.getDateInstance();
int count1=10;
int count2=15;
Calendar c=Calendar.getInstance();
c.setTime(now);
c.add(Calendar.DATE, count1);
Date addedDate1 = c.getTime();
c.setTime(addedDate1);
c.add(Calendar.DATE, count2);
Date addedDate2 = c.getTime();
System.out.println(currentDate.format(addedDate1));
System.out.println(currentDate.format(addedDate2));
}
As mentioned already in several answers/comments, doing these calculations manually is risky and error-prone.
Here is a basic example of what you need, using Joda Time library, a very stable and well-design alternative to JDK Date, Calendar. etc...
public static void main(String[] args) {
DateTime now = new DateTime();
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
int count1=10;
int count2=15;
DateTime addedDate1 = now.plusDays(count1);
DateTime addedDate2 = addedDate1.plusDays(count2);
System.out.println(fmt.print(addedDate1));
System.out.println(fmt.print(addedDate2));
}
Also, keep in mind that beside better design and clear documentation, Joda Time also is mostly thread-safe, as it always return immutable objects.
Finally, it's developed to be interoperable with JDK dates and calendars.
As mentionned by dystroy, you are not creating a new instance and this is the problem.
By the way, you could use an external library like Apache Commons Language to do this kind of logic, this is already well tested and you avoid such kind of problems. Commons Language has already an addDays method.
Even better, you could use Joda-Time which also has this kind of methods.
I am using GregorianCalander and when i tried to get todays date using the following code i am getting a date which is backdated to one month. The code i have used is as follows.
Calendar gcal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
today = getTime(gcal);
//date = dateFormat.format(calendar.getTime());
System.out.println("Today: " + today);
Please help me to solve this issue.
The output is :
Today: Thu Apr 28 00:00:00 NZST 2011
EDIT
private Date getTime(Calendar gcal) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String day = form_helper.round(gcal.get(GregorianCalendar.DAY_OF_MONTH));
String month = form_helper.round(gcal.get(GregorianCalendar.MONTH));
String year = form_helper.round(gcal.get(GregorianCalendar.YEAR));
String date = day + "/" + month + "/" + year;
System.out.println(sdf.parse(date));
return sdf.parse(date);
} catch (ParseException ex) {
Logger.getLogger(timesheet_utility.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
I think internal numbering of months starts with 0, not 1. So, you probably need to somewhere add +1.
Edit: after you showed some more code: The needed change is
String month = form_helper.round(gcal.get(GregorianCalendar.MONTH) + 1);
What does the getTime() method do? Remember that in Java, the constants for the month begin at 0 and not at 1, so Calendar.JANUARY == 0.
EDIT
Since you posted the code for getTime() I think this is the problem:
gcal.get(GregorianCalendar.MONTH) returns the month value that Java internally stores, that is, a 0-indexed month value so a value for "May" would actually be the integer "4".
When the value "4" is put back into the date parser, "April" results, since the parser interprets dates as a human would. So you simply have to add 1 to this value to ensure the parsing happens properly.
If you want a Date object that represents 12:00AM (or 00:00) for today, why not just do:
private Date getTime() {
Calendar gcal = new GregorianCalendar();
gcal.set(Calendar.HOUR_OF_DAY, 0);
gcal.set(Calendar.MINUTE, 0);
gcal.set(Calendar.SECOND, 0);
gcal.set(Calender.MILLISECOND, 0);
return gcal.getTime();
}
Here's my attempt:
package forums;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Deepak
{
public static void main(String[] args) {
try {
(new Deepak()).run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
Calendar calendar = new GregorianCalendar();
Date today = calendar.getTime();
System.out.println("Today: " + today);
}
}
and the output is the expected:
Today: Sat May 28 22:00:52 EST 2011