skip to Main Content

I recently started with Flutter and I love how it works. I need to create an App for iOS and Android for the company I work for, so I started with Flutter.

Our website uses WordPress so I am trying to use that as the backend of the App.

It is going Ok and in the App I have a News section, so I have written some code and did a WordPress API call and it works great!

I only have one Issue: the date and time format is wrong. We are in Europe so we use dd-mm-yyyy format and in my App the format is like this: yyyy-mm-dd and I need to change that but I don’t know how…

My Code:

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

Can someone please take a look and help me out?

Thanks!

2

Answers


  1. Try this

      var data = DateFormat('dd-MM-yyyy').format(DateTime.parse('2020-04-12'));
      print(data);//12-04-2020
    
    Login or Signup to reply.
  2. Fix without using external packages

    Instead of

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

    you could write something like

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

    where

    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')}";
    }
    

    Fix using intl package

    Instead of

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

    write something like

    date: json['date'] != null
      ? DateFormat('dd-MM-yyyy HH:mm:ss').format(DateTime.parse(json['date'].toString())),
      : null,
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search