Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to format string to date in Android

In my application I one string such as 2023-2-14 and I want convert this to 2023-02-14.
I write below codes:

val format = SimpleDateFormat("yyyy-MM-dd")
val date: Date = format.parse(startDateStr)
Log.e("dateLog",""+date)

But in logcat show me this : Wed Feb 15 00:00:00 GMT+03:30 2023

Why? I used this format : yyyy-MM-dd.
Why not used this format?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you are just parsing date, without a time, thus date object have set 00 for hour, day etc. now use format method for converting old String to new one

val formatAs = "yyyy-MM-dd"
var format = SimpleDateFormat(formatAs)
val date: Date = format.parse(startDateStr)
Log.e("dateLog","date:"+date)
String dateAsStringFormatted = format.format(date);
Log.e("dateLog","dateAsStringFormatted:"+dateAsStringFormatted)

some other answers in HERE

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading