skip to Main Content

How would I go about converting a datetime object (e.g. DateTime(2000, 1, 30)) to the worded date (January 30th, 2000)?

2

Answers


  1. If you look at the documentation, you can see you have the following methods exposed:

    To convert the month number into the name, you could just hold a mapping of month number to month name.

    To handle the ending of each day (st/nd/rd/th), you could also create a helper method.

    Then you can use:

    DateTime date = new DateTime(2000, 1, 30);
    String month = convertMonthToWord(date.month);
    String wordedDate = month + date.day.toString() + date.year.toString();
    
    Login or Signup to reply.
  2. Well there are a few ways to achieve this, as @tomerpacific said. Here’s one of them:

    String formatDate(DateTime date) {
        List<String> months = [
          "January",
          "February",
          "March",
          "April",
          "May",
          "June",
          "July",
          "August",
          "September",
          "October",
          "November",
          "December"
        ];
    
        final day = date.day;
        final month = months[date.month - 1];
        final year = date.year;
        String dayOrderThing = "th";
        if (day % 10 == 1 && day != 11) {
          dayOrderThing = "st";
        }
        if (day % 10 == 2 && day != 12) {
          dayOrderThing = "nd";
        }
        if (day % 10 == 3 && day != 13) {
          dayOrderThing = "rd";
        }
        return "$month $day$dayOrderThing, $year";
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search