javadatesimpledateformatdate-formatting2-digit-year

How to convert "yyyyMMdd" date format into "ccyyMMdd" simpledateformat in java


I want to convert the format from "yyyyMMdd" to "ccyyMMdd" simpledateformat in java. I am getting "c" as illegal character in java. Please help me to find the slution to convert in to "ccyyMMdd" format in java Simpledateformat

What is the differnce betwen "cc" and "yy" in java?


Solution

  • The SimpleDateFormat doesn't support c for Century. But if you simply want a 4digit year, you can use yyyy

    You can find the full list supported on the official doc of SimpleDateFormat

    //import java.util.Date;
    //import java.text.SimpleDateFormat;
    
    String s = "190415";
    SimpleDateFormat sdfIn = new SimpleDateFormat("yyMMdd");
    SimpleDateFormat sdfout = new SimpleDateFormat("yyyyMMdd");
    
    Date d = sdfIn.parse(s);
    System.out.println("OLD : " + sdfout.format(d));
    

    OLD : 20190415

    As pointed, you should also switch to the new Java Date/Time API but you will find the same problem, DateTimeFormatter doesn't have any "century" feature.

    //import java.time.LocalDate;
    //import java.time.format.DateTimeFormatter;
    
    String s = "190415";
    DateTimeFormatter dtfIn = DateTimeFormatter.ofPattern("yyMMdd");
    DateTimeFormatter dtfOut = DateTimeFormatter.ofPattern("yyyyMMdd");
    
    LocalDate ld = LocalDate.parse(s, dtfIn);
    System.out.println("NEW : " + dtfOut.format(ld));
    

    NEW : 20190415