Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Month is not printed from a date - Java DateFormat

How to get month from a date in java :

        DateFormat inputDF  = new SimpleDateFormat("mm/dd/yy");
        Date date1 = inputDF.parse("9/30/11");

        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);

        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int year = cal.get(Calendar.YEAR);

        System.out.println(month+" - "+day+" - "+year);

This code return day and year but not month.

output :

0 - 30 - 2011
like image 423
bigData Avatar asked Sep 26 '13 18:09

bigData


1 Answers

Time for someone to provide the modern answer. The other answers were good answers when the question was asked in 2013 and are still correct. Today there is no reason why you should struggle with the old, outdated and simultaneously notoriously troublesome SimpleDateFormat class. java.time, the modern Java date and time API, is so much nicer to work with:

    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/d/yy");
    LocalDate date1 = LocalDate.parse("9/30/11", inputFormatter);
    System.out.println(date1);

This prints

2011-09-30

The LocalDate class represents a date without time-of-day, exactly what you need, it matches your requirement much more precisely than the old classes Date and Calendar.

The format pattern strings used with DateTimeFormatter resemble those from SimpleDateFormat, there are a few differences. You may use uppercase MM to require two-digit month (like 09 for September) or a single M to allow the month to be written with one or two digits. Similarly dd or d for day of month. yy denotes two-digit year and is interpreted with base 2000, that is, from 2000 to 2099 inclusive (wouldn’t work for my birthday).

Link: Oracle tutorial Trail: Date Time explaining how to use java.time.

like image 138
Ole V.V. Avatar answered Oct 21 '22 02:10

Ole V.V.