Home > Software design >  How to change number to time and day of the week in dart
How to change number to time and day of the week in dart

Time:06-27

I have a json response that requires that I change '0900' to 9:00am and '1300' to 1:00pm, 5 to Friday

{

      'start': '0900',
      'end': '1300',
      'day' : 5

}

CodePudding user response:

You can do this way :

 print(_convertToTime("1300"));
 print(_convertToTime("0900"));
  
  
  
 var days ={
      0  : "Sunday",
      1  : "Monday",
      2  : "Tuesday",
      3  : "Wednesday",
      4  : "Thursday",
      5  : "Friday",
      6  : "Saturday",
 };
  
  print(days[5]);

 
 _convertToTime(String key) {
   
    var d = key.replaceAllMapped(RegExp(r".{2}"), (match) => "${match.group(0)} ");
  
  DateFormat dateFormat = DateFormat("HH mm");
  var dateTime = dateFormat.parse(d);
  DateFormat dateFormatTarget = DateFormat("hh:mm a");
  return dateFormatTarget.format(dateTime);
 }

CodePudding user response:

In this scenario, I prefer using TimeOfDay.

First, let's get start and end from map.

  late TimeOfDay start;
  late TimeOfDay end;

  TimeOfDay stringToTimeOfDay(String value) {
    return TimeOfDay(
      hour: int.tryParse(value.substring(0, 2)) ?? 0,
      minute: int.tryParse(value.substring(2)) ?? 0,
    );
  }

  @override
  void initState() {
    super.initState();

    start = stringToTimeOfDay(data["start"].toString());
    end = stringToTimeOfDay(data["end"].toString());
  }

Now the time will be in 24 formats. To convert in string and for 12 formats, you can use hourOfPeriod. I am using extension, customize the way you like.

extension TimeOfDayExtension on TimeOfDay {
  ///convert to 12h then and formatting string 00:00
  String get formatToString {
    final h = replacing(hour: hourOfPeriod).hour.toString().padLeft(2, '0');
    final m = replacing(hour: hourOfPeriod).minute.toString().padLeft(2, '0');
    return "$h:$m${period.name}";
  }
}

And use-case will be

Text(start.formatToString),
Text(end.formatToString),
  • Related