【问题标题】:Change the Date format in flutter在颤动中更改日期格式
【发布时间】:2021-08-15 01:44:50
【问题描述】:

我最近开始使用 Flutter,我喜欢它的工作原理。我需要为我工作的公司创建一个适用于 iOSAndroid 的应用程序,所以我开始使用 Flutter

我们的网站使用 Wordpress,所以我尝试将其用作应用程序的后端。

一切顺利Ok 并且在应用程序中我有一个新闻部分,所以我编写了一些代码并进行了 Wordpress API 调用而且效果很好!

我只有一个问题:datetime 格式错误。我们在欧洲,所以我们使用dd-mm-yyyy 格式,在我的应用程序中,格式是这样的:yyyy-mm-dd,我需要更改它,但我不知道如何...

我的代码:

class Post {
  final int id;
  final String title;
  final String author;
  final String excerpt;
  final String date;
  final String content;
  final String image;
  bool isSaved = false;

  Post(
    {
      this.content,
      this.id,
      this.title,
      this.excerpt,
      this.date,
      this.image,
      this.author,
    }
  );

  factory Post.fromJSON(Map<String, dynamic> json) {
    return Post(
      id: json['id'],
      title: json['title']['rendered'],
      content: json['content']['rendered'],
      date: json['date'] != null
        ? json['date'].toString().replaceFirst('T', ' ')
        : null,
      image: json['_links']['wp:featuredmedia'] != null
        ? json['_links']['wp:featuredmedia'][0]['href']
        : null,
      excerpt: json['excerpt']['rendered'],
      author: json['author'].toString()
    );
  }
}

有人可以帮我看看吗?

谢谢!

【问题讨论】:

标签: wordpress api flutter dart


【解决方案1】:

不使用外部包修复

代替

date: json['date'] != null
  ? json['date'].toString().replaceFirst('T', ' ')
  : null,

你可以写类似的东西

date: json['date'] != null
  ? getFormattedDate(json['date'].toString())
  : null,

在哪里

String getFormattedDate(String dtStr) {
  var dt = DateTime.parse(dtStr);
  
  return "${dt.day.toString().padLeft(2,'0')}-${dt.month.toString().padLeft(2,'0')}-${dt.year} ${dt.hour.toString().padLeft(2,'0')}:${dt.minute.toString().padLeft(2,'0')}:${dt.second.toString().padLeft(2,'0')}.${dt.millisecond .toString().padLeft(3,'0')}";
}

使用intl 包修复

代替

date: json['date'] != null
  ? json['date'].toString().replaceFirst('T', ' ')
  : null,

写一些类似的东西

date: json['date'] != null
  ? DateFormat('dd-MM-yyyy HH:mm:ss').format(DateTime.parse(json['date'].toString())),
  : null,

【讨论】:

    【解决方案2】:

    试试这个

      var data = DateFormat('dd-MM-yyyy').format(DateTime.parse('2020-04-12'));
      print(data);//12-04-2020
    

    【讨论】:

    • 另外@Enrico 我会在帖子中使用 DateTime 存储日期,并有一个方法或获取器来格式化它。这样您就不会失去准确比较日期的能力。
    猜你喜欢
    • 2019-07-28
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 2013-06-03
    • 2015-03-03
    • 2011-11-18
    相关资源
    最近更新 更多