Search code examples
fluttertimezoneflutter-local-notification

How to convert "MM/DD/YYYY" to TZDateTime format


I am implementing flutter local notification plugin in my todo app and I want to schedule the notification for a specific day and time, The date picker and time picker shows the date like this: 12/26/2021 and the time like this: 03:17 PM, How do I convert this to TZDateTime format


Solution

  • Try out the below code

     TZDateTime tzDateTime;
        String dateTime = getFormattedDateFromFormattedString(
            value: "12/26/2021 3:16 PM",
            currentFormat: "MM/dd/yyyy hh:mm a",
            desiredFormat: "yyyy-MM-dd HH:mm:ss");
    
        tz.initializeTimeZones();
        tzDateTime = tz.TZDateTime.parse(tz.local, dateTime);
    
        print(tzDateTime);
    }
    
    // format your given time
      getFormattedDateFromFormattedString(
          {value, String currentFormat, String desiredFormat, isUtc = true}) {
        DateTime dateTime = DateTime.now();
        if (value != null || value.isNotEmpty) {
          try {
            dateTime = DateFormat(currentFormat).parse(value, isUtc).toLocal();
          } catch (e) {
            print("$e");
          }
        }
        return dateTime.toString();
      }