[java] How do I convert the date from one format to another date object in another format without using any deprecated classes?

I'd like to convert a date in date1 format to a date object in date2 format.

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");
    Calendar cal = Calendar.getInstance();
    cal.set(2012, 8, 21);
    Date date = cal.getTime();
    Date date1 = simpleDateFormat.parse(date);
    Date date2 = simpleDateFormat.parse(date1);
    println date1
    println date2

This question is related to java

The answer is


Use SimpleDateFormat#format:

DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date);  // 20120821

Also note that parse takes a String, not a Date object, which is already parsed.


Please refer to the following method. It takes your date String as argument1, you need to specify the existing format of the date as argument2, and the result (expected) format as argument 3.

Refer to this link to understand various formats: Available Date Formats

public static String formatDateFromOnetoAnother(String date,String givenformat,String resultformat) {

    String result = "";
    SimpleDateFormat sdf;
    SimpleDateFormat sdf1;

    try {
        sdf = new SimpleDateFormat(givenformat);
        sdf1 = new SimpleDateFormat(resultformat);
        result = sdf1.format(sdf.parse(date));
    }
    catch(Exception e) {
        e.printStackTrace();
        return "";
    }
    finally {
        sdf=null;
        sdf1=null;
    }
    return result;
}

tl;dr

LocalDate.parse( 
    "January 08, 2017" , 
    DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , Locale.US ) 
).format( DateTimeFormatter.BASIC_ISO_DATE ) 

Using java.time

The Question and other Answers use troublesome old date-time classes, now legacy, supplanted by the java.time classes.

You have date-only values, so use a date-only class. The LocalDate class represents a date-only value without time-of-day and without time zone.

String input = "January 08, 2017";
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , l );
LocalDate ld = LocalDate.parse( input , f );

Your desired output format is defined by the ISO 8601 standard. For a date-only value, the “expanded” format is YYYY-MM-DD such as 2017-01-08 and the “basic” format that minimizes the use of delimiters is YYYYMMDD such as 20170108.

I strongly suggest using the expanded format for readability. But if you insist on the basic format, that formatter is predefined as a constant on the DateTimeFormatter class named BASIC_ISO_DATE.

String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE );

See this code run live at IdeOne.com.

ld.toString(): 2017-01-08

output: 20170108


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.


  private String formatDate(String date, String inputFormat, String outputFormat) {

    String newDate;
    DateFormat inputDateFormat = new SimpleDateFormat(inputFormat);
    inputDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateFormat outputDateFormat = new SimpleDateFormat(outputFormat);
    try {
        newDate = outputDateFormat.format((inputDateFormat.parse(date)));
    } catch (Exception e) {
        newDate = "";
    }
    return newDate;

}

Hope this will help someone.

 public static String getDate(
        String date, String currentFormat, String expectedFormat)
throws ParseException {
    // Validating if the supplied parameters is null 
    if (date == null || currentFormat == null || expectedFormat == null ) {
        return null;
    }
    // Create SimpleDateFormat object with source string date format
    SimpleDateFormat sourceDateFormat = new SimpleDateFormat(currentFormat);
    // Parse the string into Date object
    Date dateObj = sourceDateFormat.parse(date);
    // Create SimpleDateFormat object with desired date format
    SimpleDateFormat desiredDateFormat = new SimpleDateFormat(expectedFormat);
    // Parse the date into another format
    return desiredDateFormat.format(dateObj).toString();
}

Try this

This is the simplest way of changing one date format to another

public String changeDateFormatFromAnother(String date){
    @SuppressLint("SimpleDateFormat") DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    @SuppressLint("SimpleDateFormat") DateFormat outputFormat = new SimpleDateFormat("dd MMMM yyyy");
    String resultDate = "";
    try {
        resultDate=outputFormat.format(inputFormat.parse(date));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return resultDate;
}

    //Convert input format 19-FEB-16 01.00.00.000000000 PM to 2016-02-19 01.00.000 PM
    SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aaa");
    Date today = new Date();        

    Date d1 = inFormat.parse("19-FEB-16 01.00.00.000000000 PM");

    SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSS aaa");

    System.out.println("Out date ="+outFormat.format(d1));

Since Java 8, we can achieve this as follows:

private static String convertDate(String strDate) 
{
    //for strdate = 2017 July 25

    DateTimeFormatter f = new DateTimeFormatterBuilder().appendPattern("yyyy MMMM dd")
                                        .toFormatter();

    LocalDate parsedDate = LocalDate.parse(strDate, f);
    DateTimeFormatter f2 = DateTimeFormatter.ofPattern("MM/d/yyyy");

    String newDate = parsedDate.format(f2);

    return newDate;
}

The output will be : "07/25/2017"


Kotlin equivalent of answer answered by João Silva

 fun getFormattedDate(originalFormat: SimpleDateFormat, targetFormat: SimpleDateFormat, inputDate: String): String {
    return targetFormat.format(originalFormat.parse(inputDate))
}

Usage (In Android):

getFormattedDate(
            SimpleDateFormat(FormatUtils.d_MM_yyyy, Locale.getDefault()),
            SimpleDateFormat(FormatUtils.d_MMM_yyyy, Locale.getDefault()),
            dateOfTreatment
    )

Note: Constant values:

// 25 Nov 2017
val d_MMM_yyyy = "d MMM yyyy"

// 25/10/2017
val d_MM_yyyy = "d/MM/yyyy"

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

             String fromDateFormat = "dd/MM/yyyy";
             String fromdate = 15/03/2018; //Take any date

             String CheckFormat = "dd MMM yyyy";//take another format like dd/MMM/yyyy
             String dateStringFrom;

             Date DF = new Date();


              try
              {
                 //DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
                 DateFormat FromDF = new SimpleDateFormat(fromDateFormat);
                 FromDF.setLenient(false);  // this is important!
                 Date FromDate = FromDF.parse(fromdate);
                 dateStringFrom = new 
                 SimpleDateFormat(CheckFormat).format(FromDate);
                 DateFormat FromDF1 = new SimpleDateFormat(CheckFormat);
                 DF=FromDF1.parse(dateStringFrom);
                 System.out.println(dateStringFrom);
              }
              catch(Exception ex)
              {

                  System.out.println("Date error");

              }

output:- 15/03/2018
         15 Mar 2018