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

旧巷老猫 提交于 2021-01-27 13:26:11

问题


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.

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


回答1:


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);



回答2:


@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:

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:

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




回答3:


Use Function from import 'package:intl/intl.dart'; library.

DateFormat.Hm().format(date);

it will give a 24 hours format time 23:30




回答4:


You need to import import 'package:intl/intl.dart'; at the top of your file. Then DateFormat("h:mma") should do the trick.




回答5:


To convert UTC time to local time with specified format including date

var dateFormat = DateFormat("dd-MM-yyyy hh:mm aa"); // you can change the format here
var utcDate = dateFormat.format(DateTime.parse(uTCTime)); // pass the UTC time here
var localDate = dateFormat.parse(utcDate, true).toLocal().toString();
String createdDate = dateFormat.format(DateTime.parse(localDate)); // you will local time


来源:https://stackoverflow.com/questions/59270847/how-to-convert-time-stamp-string-from-24-hr-format-to-12-hr-format-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!