1

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

Rohith Nambiar
  • 2,957
  • 4
  • 17
  • 37
  • See [How do I convert a date/time string to a DateTime object in Dart?](https://stackoverflow.com/q/49385303/) for how to parse a `String` to a `DateTime` object. From there ,use [`TZDateTime.from`](https://pub.dev/documentation/timezone/latest/timezone.standalone/TZDateTime/TZDateTime.from.html) to convert a `DateTime` to a `TZDateTime`. – jamesdlin Dec 26 '21 at 10:16
  • While converting from dateTime to TZDateTime it asks for location, what should I specify as location. – Rohith Nambiar Dec 27 '21 at 04:41
  • 1
    I can't answer that for you.You're the one who wants to use a `TZDateTime` object, which means that you want a version of `DateTime` that uses a specific time zone that isn't UTC and that isn't the local time. You haven't indicated what time zone you want. If you care only about local or UTC times, then you can just use a normal `DateTime` object (or, if you really need a `TZDateTime` object, use the `TZDateTime.utc` or `TZDateTime.local` constructors). – jamesdlin Dec 27 '21 at 04:56

2 Answers2

3

import timezone

import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;


tz.initializeTimeZones();
tz.TZDateTime.parse(tz.local, "2012-12-26 03:17:00");
//tz.UTC

Or

tz.TZDateTime.from(DateTime(2021,12,26,03,07), tz.local);
//tz.UTC
Masum Billah Sanjid
  • 1,029
  • 1
  • 7
  • 19
0

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();
  }
Jahidul Islam
  • 11,435
  • 3
  • 17
  • 38