42

I want convert string datetime to formatted string. e.g "2018-12-14T09:55:00" to "14.12.2018 09:55" as String => Textview.text

how can I do this with kotlin or java for android ?

xingbin
  • 27,410
  • 9
  • 53
  • 103
withoutOne
  • 723
  • 1
  • 6
  • 14
  • 2
    What have you done already? – Geno Chen Dec 14 '18 at 14:02
  • what the -2 ? really?? – withoutOne Dec 15 '18 at 07:40
  • 2
    I didn’t downvote. My guess is the now -3 are because of a lack of search and research effort. How to change a date-time string from one format to another has been asked and answered here on Stack Overflow many times and has also been shown in many other places on Internet. So probably a not too great search effort would have giving you a better starting point faster, maybe enough that you could adapt the code snippets found yourself, and if that posed a problem, your question here would have looked quite differently. – Ole V.V. Dec 15 '18 at 08:33

8 Answers8

75

Parse it to LocalDateTime then format it:

LocalDateTime localDateTime = LocalDateTime.parse("2018-12-14T09:55:00");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
String output = formatter.format(localDateTime);

If this does not work with api21, you can use:

SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
String output = formatter.format(parser.parse("2018-12-14T09:55:00"));

or import ThreeTenABP.

xingbin
  • 27,410
  • 9
  • 53
  • 103
  • 4
    I try this already. But i give an error on LocalDateTime.parse : "call requires api level 26, current api is 21" – withoutOne Dec 15 '18 at 07:40
  • Does this work on API level 21? It does when you add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to you rproject and make sure you import `org.threeten.bp.LocalDateTime` and `org.threeten.bp.format.DateTimeFormatter`. – Ole V.V. Dec 15 '18 at 07:42
  • I remove 'java.time.format.DateTimeFormatter' and other conflicts. I use only you words. This is work now. Thanks 孙兴斌 and Ole. why am I -3 ? – withoutOne Dec 15 '18 at 08:23
  • 2
    Great that it works. I read in your profile that you’re in İzmir, Turkey, so you are aksing for the date-time format for your locale (wise). This is built into Java. So I suggest `DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.forLanguageTag("tr"));`. It’s longer, but avoiding hand-typing the format pattern string is worthwhile, and this also better lends itself to internationalization. – Ole V.V. Dec 15 '18 at 08:41
  • 1
    Best answer so far. Thank you – Ticherhaz FreePalestine Aug 21 '19 at 04:55
  • The question is asked for API 21. LocalDateTime was added in API 26. – Dhir Pratap May 03 '20 at 15:22
  • 5
    You don't need to use ThreeTenABP, refer to this instead: https://developer.android.com/studio/write/java8-support#library-desugaring – Lasse Meyer Sep 07 '20 at 20:06
  • Better to use `SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault())` instead. – Mihae Kheel Apr 08 '21 at 12:32
  • if 'api 21 problem' - check https://stackoverflow.com/a/60687913/1367449 – Grzegorz Dev Aug 25 '22 at 07:03
  • Update: The *java.time* classes are built into Android 26+. The latest Android tooling provides **most of the *java.time* functionality to earlier Android via “API desugaring”**. So no reason to resort to the terrible legacy date-time classes. – Basil Bourque Apr 02 '23 at 06:46
29

Kotlin API levels 26 or greater:

val parsedDate = LocalDateTime.parse("2018-12-14T09:55:00", DateTimeFormatter.ISO_DATE_TIME)
val formattedDate = parsedDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm"))

Below API levels 26:

val parser =  SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
val formatter = SimpleDateFormat("dd.MM.yyyy HH:mm")
val formattedDate = formatter.format(parser.parse("2018-12-14T09:55:00"))
arifng
  • 726
  • 1
  • 12
  • 22
4

If you have a date-time that represents a value in a specific time zone but the zone is not encoded in the date-time string itself (eg, "2020-01-29T09:14:32.000Z") and you need to display this in the time zone you have (eg, CDT)

val parsed = ZonedDateTime.parse("2020-01-29T09:14:32.000Z", DateTimeFormatter.ISO_DATE_TIME).withZoneSameInstant(ZoneId.of("CDT"))

That parsed ZoneDateTime will reflect the time zone given. For example, this date would be something like 28 Jan 2020 at 8:32am.

P. Ent
  • 1,654
  • 1
  • 12
  • 22
3

In kotlin u can do this way to format string to date :-

val simpleDateFormat = SimpleDateFormat("yyyy/MM/dd HH:mm:ss",Locale.getDefault())
val date = SimpleDateFormat("yyyy/MM/dd", Locale.getDefault()).format(simpleDateFormat.parse("2022/02/01 14:23:05")!!)

Should import java.text.SimpleDateFormat For SimpleDateFormat Class to work on api 21

1

java.time

The java.util date-time API and their corresponding parsing/formatting type, SimpleDateFormat are outdated and error-prone. In March 2014, the modern Date-Time API was released as part of the Java 8 standard library which supplanted the legacy date-time API and since then it is strongly recommended to switch to java.time, the modern date-time API.

You do not need a DateTimeFormatter to parse your date-time string

java.time API is based on ISO 8601 and therefore you do not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format (e.g. your date-time string, 2018-12-14T09:55:00).

However, your desired output, 14.12.2018 09:55 is not in ISO 8601 standard format and therefore, you need a DateTimeFormatter to get a string in the desired format.

Demo:

class Main {
    public static void main(String[] args) {
        LocalDateTime ldt = LocalDateTime.parse("2018-12-14T09:55:00");
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm", Locale.ENGLISH);
        String output = ldt.format(formatter);
        System.out.println(output);
    }
}

Output:

14.12.2018 09:55

ONLINE DEMO

Here, you can use y instead of u but I prefer u to y.

Learn more about the modern Date-Time API from Trail: Date Time.


* If you are working on an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

Here is Kotlin One Liner,It will return empty string if input date cannot be parsed.

fun String.getDateInAnotherFormat(inputFormat: String,outputFormat: String):String = SimpleDateFormat(inputFormat, Locale.getDefault()).parse(this)?.let { SimpleDateFormat(outputFormat,Locale.getDefault()).format(it) }?:""

Usage:

var dateStr = "2000-12-08"
dateStr.getDateInAnotherFormat("yyyy-MM-dd","MMM dd YYYY")
Gowtham K K
  • 3,123
  • 1
  • 11
  • 29
  • That line is too long to be practical to read. Also consider using [desugaring](https://developer.android.com/studio/write/java8-support-table) and java.time, the modern Java date and time API, so you can do without the old and notoriously troublesome `SimpleDateFormat`. – Ole V.V. Aug 13 '22 at 06:43
0

Kotlin: Date time format

fun getApiSurveyResponseDateConvertToLocal(date: String?): String? {
        return try {
            val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US)
            val outputFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)
            val datee = date?.let { inputFormat.parse(it) }
            datee?.let { outputFormat.format(it) }
        } catch (e: ParseException) {
            e.printStackTrace()
            ""
        }
    }

Java: Date time format

public static String getApiSurveyResponseDateConvertToLocal(String date) {

try {
    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
    SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
   Date datee = inputFormat.parse(date);
    return outputFormat.format(datee);
} catch (ParseException e) {
    e.printStackTrace();
    return "";
}}
  • 1
    FYI, you using terrible date-time classes that are now legacy, supplanted years ago by the modern *java.time* classes defined in JSR 310. – Basil Bourque Apr 02 '23 at 06:43
0

Kotlin : Time format converter 24 hrs to 12 hrs

private const val SERVER_TIME_FORMAT = "hh:mm a"
    private const val SERVER_TIME_24HR_FORMAT = "HH:mm"

fun getEmpTimeLineFormat(date: String?): String? {
        val serverFormat = SimpleDateFormat(
            SERVER_TIME_24HR_FORMAT,
            Locale.ENGLISH
        )
        val timelineFormat = SimpleDateFormat(
            SERVER_TIME_FORMAT,
            Locale.ENGLISH
        )
        return try {
            serverFormat.parse(date)?.let { timelineFormat.format(it) }
        } catch (e: ParseException) {
            e.printStackTrace()
            ""
        }
    }