64

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
Phoenix
  • 8,695
  • 16
  • 55
  • 88

10 Answers10

154

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.

João Silva
  • 89,303
  • 29
  • 152
  • 158
  • 1
    you'd need to wrap Date parsedDate = simpleDateFormat1.parse(formattedDate); with try catch as it'd throw parseexception. – PermGenError Sep 19 '12 at 22:09
  • 1
    What are the exact inputs you are trying to parse? Try this demo http://ideone.com/Hr6B0. Perhaps you are passing an invalid `Date`? – João Silva Sep 19 '12 at 22:11
  • My input is a string of this format August 21, 2012 and I need to save it as another string of format 20120821 – Phoenix Sep 19 '12 at 22:12
  • 2
    @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. – João Silva Sep 19 '12 at 22:12
  • 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); – Phoenix Sep 19 '12 at 22:14
  • @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. – João Silva Sep 19 '12 at 22:15
  • 5
    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. – Joe C Mar 24 '18 at 10:10
13

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

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    It should be noted that Android apps targeting API level 26 or above (Android 8.0, O) [can use `java.time`](https://developer.android.com/reference/java/time/package-summary) directly without using ThreeTenABP. Disclaimer: I might have been involved in that. – Joachim Sauer May 19 '21 at 22:18
  • 2
    @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. – Basil Bourque May 19 '21 at 22:54
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"

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
KayV
  • 12,987
  • 11
  • 98
  • 148
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;
}
Community
  • 1
  • 1
Sunil
  • 3,785
  • 1
  • 32
  • 43
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"
Shubham AgaRwal
  • 4,355
  • 8
  • 41
  • 62
  • 1
    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](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Aug 29 '18 at 14:18
  • 1
    I didn't knew about that. I will check it soon – Shubham AgaRwal Aug 29 '18 at 15:58
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;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ThmHarsh
  • 601
  • 7
  • 7
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;

}
Deepak Kataria
  • 554
  • 3
  • 10
  • 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. – Ole V.V. Nov 11 '19 at 20:34
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();
}
Dinesh Lomte
  • 569
  • 7
  • 5
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
-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));
Karthik M
  • 89
  • 5
  • 1
    SimpleDateFormat is limited to parsing millisecond precision, and will corrupt the minutes/seconds if asked to go beyond that. – Robert Dean May 13 '16 at 12:24