4

I want to read a date in the format YYYY-MM-DD.

But if I enter date say for example 2008-1-1, I want to read it as 2008-01-01.

Can anybody help me? Thanks in advance

Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
user48094
  • 10,481
  • 12
  • 36
  • 30

5 Answers5

11

Or use the much better Joda Time lib.

    DateTime dt = new DateTime();
    System.out.println(dt.toString("yyyy-MM-dd"));

    // The ISO standard format for date is 'yyyy-MM-dd'
    DateTimeFormatter formatter = ISODateTimeFormat.date();
    System.out.println(dt.toString(formatter));
    System.out.println(formatter.print(dt));

The Date and Calendar API is awful.

Ludwig Wensauer
  • 1,885
  • 3
  • 32
  • 43
7

Use SimpleDateFormat.

[Edited]

Few sample codes.

mmoya
  • 1,901
  • 1
  • 21
  • 30
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
  • 4
    Just have to be careful of the threading problems with that! I've had the weirdest bugs arise from use of SimpleDateFormat – chillysapien Jan 05 '09 at 10:40
7

Adeel's solution is fine if you need to use the built-in Java date/time handling, but personally I'd much rather use Joda Time. When it comes to formats, the principle benefit of Joda Time is that the formatter is stateless, so you can share it between threads safely. Sample code:

DateTimeFormatter parser = DateTimeFormat.forPattern("YYYY-M-D");
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-DD");

DateTime dt = parser.parseDateTime("2008-1-1");
String formatted = formatter.print(dt); // "2008-01-01"
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3
import java.text.*;

public class Test
{

    public static void main(String args[])
    {
        try
        {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");  
            System.out.println(sdf.parse(args[0]).toString());
        }
                catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

This works OK, no matter if you write as argument "2008-1-1" or "2008-01-01".

Fernando Miguélez
  • 11,196
  • 6
  • 36
  • 54
1

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d", Locale.ENGLISH);
        String input = "2008-1-1";
        LocalDate date = LocalDate.parse(input, dtfInput);
        System.out.println(date);
    }
}

Output:

2008-01-01

ONLINE DEMO

Notes:

  1. Use y (which specifies year-of-era) instead of Y (which specifies week-based-year).
  2. Use d (which specifies day-of-month) instead of D (which specifies day-of-year).
  3. For parsing, a single u can cater to both, two-digit and four-digit year representation. Similarly, a single M can cater to both one-digit and two-digit months. DateTimeFormatter processes other letters in a similar fashion.
  4. Here, you can use y instead of u but I prefer u to y.
  5. You must have noticed that I have not used a DateTimeFormatter for the output string. It is because the LocalDate#toString already returns the string in the ISO-8601 format, uuuu-MM-dd (which is also your desired pattern).

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110