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
Asked
Active
Viewed 859 times
1
-
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
-
1I 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 Answers
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
-
I get the error: _TypeError (type 'Null' is not a subtype of type 'TZDateTime') – Rohith Nambiar Dec 26 '21 at 11:42
-
I think you miss something, please check out [dartpad](https://dartpad.dartlang.org/?id=a2dc80fdac4b7fd5b098b48dbd7afbf9) – Jahidul Islam Dec 26 '21 at 11:46
-
This returns a string but it should be in TZDateTime, So I tried TZDateTime.parse method, it asks for location, what should I do for location – Rohith Nambiar Dec 26 '21 at 12:17
-
i hope it will help you, please check this [answer](https://stackoverflow.com/questions/64305469/how-to-convert-datetime-to-tzdatetime-in-flutter) – Jahidul Islam Dec 26 '21 at 12:25
-
-
-
-