Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert time stamp string from 24 hr format to 12 hr format in dart?

I am working on flutter application where i have to show time stamps but the response i got from api is in 24 hr format and i want to display time in 12 hr format in my application.Here is the json response from api

And i want to display on application in this format I want in this format Can you please help me regarding the easiest way of doing the formatting from 24 hr to 12 hr?

like image 696
Umair Avatar asked Dec 10 '19 15:12

Umair


People also ask

How do I convert a dart timestamp to DateTime?

DateTime to TImestampThe millisecondsSinceEpoch property of the DateTime class gives us the number of milliseconds since the “Unix epoch” 1970-01-01T00:00:00Z (UTC). This is the timestamp in milliseconds. If you want the timestamp in seconds, just divide the result by 1000.

How do you convert to 24 hour format in flutter?

Convert it to 24 hours format If we set alwaysUse24HourFormat to true, it might convert to 24 hours format but we need to clone the default setting and then change the value in somewhere.


2 Answers

Dart intl framework helps you to format date/time into any type you want.

https://pub.dev/packages/intl

Especially for your case, you can use this code.

DateFormat("h:mma").format(date);
like image 139
Ares Avatar answered Sep 28 '22 01:09

Ares


@Umair, as Sam pointed out, you can use intl package and can use jm() function without explicitly declaring the format like so,

For default DateTime

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('Test'),
            ),
            body: Padding(
                padding: EdgeInsets.all(20.0),
                child: Center(
                  child: Text(new DateFormat.jm().format(DateTime.now()), style: TextStyle(fontSize: 18.0),),
                )
            )
        ));
  }
}

Screenshot: screenshot

For 24 hr timestamp string

class MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    String timeStamp24HR = "2020-07-20T18:15:12";

    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('Test'),
            ),
            body: Padding(
                padding: EdgeInsets.all(20.0),
                child: Center(
                  child: Text(new DateFormat.jm().format(DateTime.parse(timeStamp24HR)), style: TextStyle(fontSize: 18.0),),
                )
            )
        ));
  }
}

Screenshot: 24hr time string

More info on Flutter's parse method here - https://api.flutter.dev/flutter/dart-core/DateTime/parse.html

like image 26
Pro Avatar answered Sep 28 '22 02:09

Pro