0

I am trying to parse a string to a SimpleDateFormat, however it doesn't display the yyyy-MM-dd format that I made.

This is the result:

Sun Jun 23 00:00:00 GMT+08:00 2019

This is what I need:

2019-07-23

Here's my code:

 onDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            String date = year+"-"+month+"-"+dayOfMonth;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            try {
                Date datex = format.parse(date);
                System.out.println(datex);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    };
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
kwestionable
  • 496
  • 2
  • 8
  • 23
  • 1
    what is the output you got? – sasikumar Jul 23 '19 at 05:21
  • Have a look [this](https://stackoverflow.com/a/35710436/5110595). – Hemant Parmar Jul 23 '19 at 05:22
  • 1
    it's on the post @sasikumar – kwestionable Jul 23 '19 at 05:22
  • why you need to format String date = year+"-"+month+"-"+dayOfMonth; is already giving you date in yyyy-mm-dd format in this case of yours – Neha Rathore Jul 23 '19 at 05:23
  • Yes it does return a value, however I am following a formatted date. the ` year+"-"+month+"-"+dayOfMonth` is returning the value of `2019-7-23` and what I need is `2019-07-23` – kwestionable Jul 23 '19 at 05:25
  • 1
    just add 1 more line format.format(datex) -- you had parsed date but not formatted it in the format you want – Neha Rathore Jul 23 '19 at 05:30
  • I got it working now, thanks @NehaRathore – kwestionable Jul 23 '19 at 05:31
  • As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Jul 23 '19 at 06:31
  • Possible duplicate of [display Java.util.Date in a specific format](https://stackoverflow.com/questions/6262310/display-java-util-date-in-a-specific-format) – Ole V.V. Jul 23 '19 at 06:32

6 Answers6

1

More simpler way to do this by following,

        String date = year+"-"+month+"-"+dayOfMonth;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        try {
            Date datex = format.parse(date);
            String outputDate = format.format(datex);
            System.out.println(outputDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
DHAVAL A.
  • 2,251
  • 2
  • 12
  • 27
1

java.time and ThreeTenABP

This will give you the output that you asked for, 2019-07-23 (with correct month number, 07, and with leading zero):

onDateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            LocalDate date = LocalDate.of(year, month + 1, dayOfMonth);
            String dateString = date.toString();
            System.out.println(dateString);
        }
    };

I am using LocalDate from java.time, the modern Java date and time API. We need to add one to the month because DatePicker confusingly counts months from 0 for January through 11 for December, while LocalDate numbers months the same way humans do. LocalDate.toString() produces the yyyy-MM-dd format you asked for. It conforms with ISO 8601.

What went wrong in your code?

First because, as mentioned, DatePicker numbers months from 0, you got the wrong month, 6 for July, so it was printed as June in your output. Second, formatting the date into a string, parsing it into a Date and printing that Date as a string is over-complicating things. Also Date.toString() always produces the format you saw, EEE MMM dd HH:mm:ss zzz yyyy. To produce a different string from that you would have needed to format it explicitly.

In any case both SimpleDateFormat and Date are poorly designed and long outdated. And the modern date and time API is so much nicer to work with. I recommend it warmly.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

Try this its working fine for me to long date convert to a simple date.

public String getTimeStamp(long timeinMillies) {
            String date = null;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // modify format
            date = formatter.format(new Date(timeinMillies));
            System.out.println("Today is " + date);

            return date;
        }

Or use this

SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date(year, month, day);
String strDate = dateFormatter.format(d);

Thanks, Happy Coding...

Mayur
  • 735
  • 4
  • 14
  • yes you are putting String date = year+"-"+month+"-"+dayOfMonth; wrong formation in method just put long date value – Mayur Jul 23 '19 at 05:22
  • Sun Jun 23 00:00:00 GMT+08:00 2019 this is long value and you are putting string value that's why you are getting FATAL EXCEPTION – Mayur Jul 23 '19 at 05:23
  • No, even if you insist on using the poorly designed and long outdated classes `Date` and `SimpleDateFormat`, you still should *not* use the deprecated `Date(int, int, int)` constructor (it’s been deprecated for decades now). – Ole V.V. Jul 23 '19 at 06:57
0

Add this function in extension it will work

   fun Context.getFormattedDate(
        inputFormat: String = "yyyy-MM-dd",
        outputFormat: String,
        inputDate: String,
        locale: Locale = Locale("EN")
    ): String {
        val inputFormat = inputFormat
        var outputFormat = outputFormat

        if (outputFormat == "") {
            outputFormat = "EEEE d 'de' MMMM 'del' yyyy" // if inputFormat = "", set a default output format.
        }
        var parsed: Date? = null
        var outputDate = ""

        val dfInput = SimpleDateFormat(inputFormat, locale)
        val dfOutput = SimpleDateFormat(outputFormat, locale)

        try {
            parsed = dfInput.parse(inputDate)
            outputDate = dfOutput.format(parsed)
        } catch (e: Exception) {
            Log.e("formattedDateFromString", "Exception in formate Date From string(): " + e.message)
            e.printStackTrace()
        }
        return outputDate

    }
Jahanvi Kariya
  • 377
  • 3
  • 14
0

This will you the desired result

String date = year+"-"+month+"-"+dayOfMonth;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", 

    Locale.getDefault());
            Date datex = null;
            try {
                datex = format.parse(date);
                String formattedDate=format.format(datex);
                Log.e("FormattedDate",formattedDate);
            } catch (ParseException e) {
                e.printStackTrace();
            }
DHAVAL A.
  • 2,251
  • 2
  • 12
  • 27
Lakhwinder Singh
  • 6,799
  • 4
  • 25
  • 42
0

Use this function for any conversion of date,it will work :)

In Java

/**
 * Changes date format from one format to another format.
 *
 * @param fromFormat format of received date string.
 * @param toFormat   format of returned(needed) date string.
 * @param date       date whose format is to be changed in string.
 * @return date string formatted into toFormat
 */
public static String changeDateFormat(String fromFormat, String toFormat, String date) {
    SimpleDateFormat toDateFormat = new SimpleDateFormat(toFormat);
    SimpleDateFormat dateFormat = new SimpleDateFormat(fromFormat);

    try {
        return toDateFormat.format(dateFormat.parse(date));
    } catch (Exception e) {
        e.printStackTrace();
        return "NA";
    }
}

In Kotlin

fun changeDateFormat(fromFormat: String, toFormat: String, date: String): String {
        val toDateFormat = SimpleDateFormat(toFormat)
        val dateFormat = SimpleDateFormat(fromFormat)
        return try {
            toDateFormat.format(dateFormat.parse(date))
        } catch (e: Exception) {
            e.printStackTrace()
            "NA"
        }

    }

In Code

AppLogs.e(
        "DATE",
        Utility.changeDateFormat("E MMM dd HH:mm:ss Z yyyy", "yyyy-MM-dd", "Sun Jun 23 00:00:00 GMT+05:30 2019")
    )
Ashish
  • 116
  • 4