如何在 dart 中将时间戳字符串从 24 小时格式转换为 12 小时格式?

Uma*_*air 6 formatting timestamp type-conversion dart flutter

我正在处理颤振应用程序,我必须在其中显示时间戳,但我从 api 得到的响应是 24 小时格式,我想在我的应用程序中以 12 小时格式显示时间。这是来自 api 的 json 响应

我想以这种格式在应用程序上显示 我想要这种格式 您能否帮助我了解从 24 小时到 12 小时进行格式化的最简单方法?

Are*_*res 10

Dartintl框架可帮助您将日期/时间格式化为您想要的任何类型。

https://pub.dev/packages/intl

特别是对于您的情况,您可以使用此代码。

DateFormat("h:mma").format(date);
Run Code Online (Sandbox Code Playgroud)


Shy*_*dda 8

将 UTC 时间转换为指定格式(包括日期)的本地时间

导入以下包:

package:intl/intl.dart';
Run Code Online (Sandbox Code Playgroud)

转换如下:

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 get local time
Run Code Online (Sandbox Code Playgroud)


Ram*_*lty 6

您可以简单地使用 TimeOfDay 类:

var time = TimeOfDay.fromDateTime(DateTime.now());
print(time.hourOfPeriod);
print(time.minute);
print(time.period);
Run Code Online (Sandbox Code Playgroud)


sam*_*sam 5

您需要import 'package:intl/intl.dart';在文件顶部导入。然后DateFormat("h:mma")应该做的伎俩。


Pro*_*Pro 5

@Umair,正如 Sam 指出的那样,您可以使用intl包并且可以使用 jm() 函数,而无需像这样明确声明格式,

默认情况下 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),),
                )
            )
        ));
  }
}
Run Code Online (Sandbox Code Playgroud)

截屏: 截屏

对于 24 小时时间戳字符串

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),),
                )
            )
        ));
  }
}
Run Code Online (Sandbox Code Playgroud)

截屏: 24 小时时间字符串

有关 Flutter 解析方法的更多信息 - https://api.flutter.dev/flutter/dart-core/DateTime/parse.html


小智 5

使用import 'package:intl/intl.dart';库中的函数。

DateFormat.Hm().format(date);

它会给出 24 小时格式的时间23:30


小智 5

DateTime now = DateTime.now();
String formattedDate = DateFormat().add_yMMMEd().add_jms().format(now);
Run Code Online (Sandbox Code Playgroud)

提交时间:2022年7月14日星期四 4:50:24 PM