How do I convert the date from one format to another date object in another format without using any deprecated classes?
Asked Answered
C

10

65

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
Checky answered 19/9, 2012 at 22:0 Comment(1)
I have created a simple method to do this. refer to https://mcmap.net/q/297837/-how-to-convert-date-to-a-particular-format-in-androidDoha
N
155

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.

Nicholson answered 19/9, 2012 at 22:1 Comment(7)
you'd need to wrap Date parsedDate = simpleDateFormat1.parse(formattedDate); with try catch as it'd throw parseexception.Dyal
What are the exact inputs you are trying to parse? Try this demo ideone.com/Hr6B0. Perhaps you are passing an invalid Date?Rhombohedron
My input is a string of this format August 21, 2012 and I need to save it as another string of format 20120821Checky
@Phoenix: Are you setting the Locale to Locale.ENGLISH of the first SimpleDateFormat? Otherwise, if you are on a non-english Locale, August will not be parsed correctly and will throw a ParseException.Rhombohedron
This is what I did. I want the end output to be "20120821" SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy",Locale.ENGLISH); SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd"); Date date1 = simpleDateFormat.format("August 21, 2012"); String formattedDate = simpleDateFormat1.format(date1); Date parsedDate = simpleDateFormat1.parse(formattedDate);Checky
@Phoenix: format is to format the output; to parse a Date from a String you need to use parse. So, instead of Date date1 = simpleDateFormat.format("August 21, 2012"), you should have Date date1 = simpleDateFormat.parse("August 21, 2012") as in my sample code.Rhombohedron
While this answer was the best answer at the time, I should advise visitors coming to the site now that the classes used are considered legacy these days. The answers which refer to Java 8 are now the preferred way to do this.Differentiation
R
14

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.

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

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

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

Resultant answered 15/2, 2017 at 4:28 Comment(2)
It should be noted that Android apps targeting API level 26 or above (Android 8.0, O) can use java.time directly without using ThreeTenABP. Disclaimer: I might have been involved in that.Badmouth
@JoachimSauer So noted in a fresh edit to this Answer; thanks for the comment. And I'm sure all the Android developers are grateful for your work on java.time functionality.Resultant
C
7

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"

Cobbie answered 26/7, 2017 at 9:58 Comment(0)
C
5

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;
}
Carnivore answered 10/3, 2018 at 17:16 Comment(0)
N
3

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"
Nachison answered 29/8, 2018 at 10:28 Comment(2)
While SimpleDateFormat is not officially deprecated yet, it is certainly both long outdated and notoriously troublesome. Today we have so much better in java.time, the modern Java date and time API and its DateTimeFormatter. Yes, you can use it on Android. For older Android see How to use ThreeTenABP in Android Project.Raven
I didn't knew about that. I will check it soonNachison
K
2

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;
}
Knowles answered 5/2, 2015 at 9:5 Comment(0)
V
2
  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;

}
Vevina answered 11/11, 2019 at 6:48 Comment(1)
While not officially deprecated, the classes DateFormat, SimpleDateFormat and TimeZone are poorly designed and long outdated. Please don’t suggest using them in 2019, it’s a bad idea.Raven
O
0

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();
}
Offensive answered 30/3, 2017 at 9:55 Comment(0)
B
0
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
Bridgman answered 15/3, 2018 at 5:18 Comment(0)
G
-1
    //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));
Going answered 19/2, 2016 at 21:2 Comment(1)
SimpleDateFormat is limited to parsing millisecond precision, and will corrupt the minutes/seconds if asked to go beyond that.Lightship

© 2022 - 2024 — McMap. All rights reserved.