-1

I am Extracting the month From this String by using Substring.

String main="2014-07-30 13:30:00";
String month=main.substring(5, 7);

Bt now i wanted to limit the month i.e.

if(month<0 || month>12)
{
sysout("Wrong Input");
}

So what Shoud i Do???

Jens
  • 67,715
  • 15
  • 98
  • 113

2 Answers2

0
public static void main(String[] args) {
    String main="2014-11-30 13:30:00";
    String pattern = "yyyy-MM-dd HH:mm:ss";
    DateFormat formatter = new SimpleDateFormat(pattern);
    try {
        Date date = formatter.parse(main);
        if(!main.equals(formatter.format(date)))
            System.out.println("Wrong input");
    } catch (ParseException e) {
        System.out.println("Wrong input");
    }
}
dung ta van
  • 988
  • 8
  • 13
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque May 08 '17 at 09:28
0

Using java.time

The modern approach is with the java.time classes.

Parse the string as a date-time object, a LocalDateTime in this particular case. If the parsing fails, you know the input was wrong.

To parse, alter your input to fully comply with the ISO 8601 standard. This means replacing that SPACE in the middle with a T. The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

String input = "2014-07-30 13:30:00".replace( " " , "T" );

Catch the exception thrown if the input is faulty such as the month number being out of the range of 1-12.

try {
    LocalDateTime ldt = LocalDateTime.parse( input );
} catch (DateTimeParseException e ) {
    // Handle this error, when we receive faulty input.
    System.out.println( "Wrong input." ); 
}

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.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

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.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154