Kotlin Android / Java String DateTime Format, API21
Asked Answered
A

8

44

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 ?

Abroms answered 14/12, 2018 at 13:58 Comment(3)
What have you done already?Hypocaust
what the -2 ? really??Abroms
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.Ticktacktoe
D
77

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.

Diarrhea answered 14/12, 2018 at 14:1 Comment(10)
I try this already. But i give an error on LocalDateTime.parse : "call requires api level 26, current api is 21"Abroms
Does this work on API level 21? It does when you add ThreeTenABP to you rproject and make sure you import org.threeten.bp.LocalDateTime and org.threeten.bp.format.DateTimeFormatter.Ticktacktoe
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 ?Abroms
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.Ticktacktoe
Best answer so far. Thank youEnchantress
The question is asked for API 21. LocalDateTime was added in API 26.Asoka
You don't need to use ThreeTenABP, refer to this instead: developer.android.com/studio/write/…Spanking
Better to use SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault()) instead.Doubs
if 'api 21 problem' - check https://mcmap.net/q/375036/-android-date-in-api-level-21-closedInterstitial
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.Crypto
T
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"))
Tosha answered 12/7, 2019 at 15:34 Comment(3)
What would you do for api lvl below 24? It seems that SimpleDateFormat is not an optionDevest
Which package? java.text or android.icu.text?Wadlinger
Seems to be java.text, android.icu.text is just full of stubs, huh!?Wadlinger
T
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.

Tuinenga answered 29/1, 2020 at 18:7 Comment(0)
E
4

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

Ernst answered 7/1, 2022 at 15:57 Comment(0)
W
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.

Woolfolk answered 13/4, 2023 at 12:17 Comment(0)
P
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")
Pademelon answered 12/8, 2022 at 11:2 Comment(1)
That line is too long to be practical to read. Also consider using desugaring and java.time, the modern Java date and time API, so you can do without the old and notoriously troublesome SimpleDateFormat.Ticktacktoe
R
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 "";
}}
Rusticate answered 23/3, 2023 at 6:33 Comment(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.Crypto
R
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()
            ""
        }
    }
Rusticate answered 12/4, 2023 at 6:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.