3

how to check whether the 30 or 31th day of a month does exist or not.

31.09.2016 doesn't exist but will be shown as 01.10.2016 in Java and Javascript. Even with the correct locales etc. Any solutions in javascript or java is welcome since an ajax request can solve this as well.

Thanks in advance

Moonstar
  • 247
  • 1
  • 4
  • 13
  • 1
    Change the string to a date, and back to a string. If the strings are equal, it's a valid date; otherwise, it's not. – Andy Turner Sep 30 '16 at 12:29
  • I thought that there could be a simpler solution. That was my first thought as well. Thank you very much. – Moonstar Sep 30 '16 at 12:33
  • @AndyTurner so does the date 12/31/2016 not exist then? Because it wouldn't in the states. Of course that one is obvious, so it might be detected correctly - try it with 05/06/2016. – VLAZ Sep 30 '16 at 12:34
  • 1
    @vlaz well, I don't know - *does it* exist? Depends on your requirements as to whether you want to handle different formats. That said, there's only 6 ways to order year, month and day - you could always try all six permutations and see if any one is valid, and it'd still be an awful lot faster than an AJAX call. – Andy Turner Sep 30 '16 at 12:40
  • Note the 29th is not valid for some February in some years. BTW https://en.wikipedia.org/wiki/February_30 – Peter Lawrey Sep 30 '16 at 12:42
  • @AndyTurner yes, it is a valid format. The question explicitly mentions "with correct locales". Therefore, users are in charge of the date, and thus they will most likely use their regional format. MM/DD/YYYY is valid in the USA but not in, say, the UK, where the format is DD/MM/YYYY. That's _assuming_ a full year is expected, 05/06/16 is also a valid date if we take short years. In that case, your suggestion of trying all permutation will not work for 04/31/16 - it _could_ be a valid format but not in the UK using short years. – VLAZ Sep 30 '16 at 12:46
  • @Moonstar Ask a separate Question for JavaScript, but search before posting. For Java, this has been asked multiple times already. So I am closing as a duplicate. – Basil Bourque Oct 01 '16 at 15:28
  • @Basil Bourque ok sry couldn't find an answer... – Moonstar Oct 02 '16 at 14:12

5 Answers5

7

I think you should use the momentjs library for any kind of date manipulation in javascript: MomentJS

var date = moment('31.09.2016','DD.MM.YYYY');
console.log(date.isValid()); // This will print false in case of an invalid date

Edit: Created a plunker so you can try it out: plunker example . Check the javascript console

nagyf
  • 859
  • 5
  • 17
  • Perfect. Works as it should. Thank you very much. Validation is done by inputmask but wasn't capable to check this special case. – Moonstar Sep 30 '16 at 12:47
  • For future visitors: Day.js is another popular MomentJS alternative: https://day.js.org/docs/en/parse/is-valid#docsNav – aderchox Jan 20 '23 at 18:41
3

The answer from @nagyf is pretty good for js, on the java side you should set the leninent property to false in the DateFormat and then you will get an ParseException if the date is invalid.

Example:

final String d = "31/09/2016";
final DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
df.setLenient(false);
final Date parsDate = df.parse(d);
System.out.println(d);
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

Here is solution for Java

try{
    String date = "31/9/2016";
    Data d = new Date();
    DateFormat df = new SimpleDateFormat("đd/MM/yyyy");
    df.setLenient(false);
    d = df.parse(date);
catch(ParseException ex){
    System.out.println("Invalid Date");
}
Tinh Huynh
  • 76
  • 2
  • 6
  • 1
    Don't catch `Exception`: catch the most specific exception you can (i.e. `ParseException`), so that you don't conflate unrelated problems. – Andy Turner Sep 30 '16 at 13:00
  • @AndyTurner Agreed with you. I forgot that exception, thanks for reminding me :) – Tinh Huynh Sep 30 '16 at 13:12
0

An alternative way of checking lastDay given vs what is actually on calendar would be if you are working with a valid date and a given lastDay : (not in javascript in groovy/java)

int day=31
Date givenDate = new Date() 
Calendar cal = Calendar.instance
cal.setTime(givenDate)
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH)
if (day > lastDay) {
 // fail throw exception
}
//otherwise good to go
V H
  • 8,382
  • 2
  • 28
  • 48
0

java.time

The YearMonth class is handy for this. This object can provide a LocalDate object representing the last day of the month. You can ask that object for its day-of-month number.

int numberOfLastDay =
    YearMonth.of( 2016 , Month.SEPTEMBER )
        .atEndOfMonth()
        .getDayOfMonth() ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154