How to convert a simple string to a DateTime object? - flutter

I am tring to convert a simple string into a date time but it is showing invalid exception. Here's the code :
void main() {
String date = '12';
date = DateTime.parse(date).toString();
print(date);
}
Can anyone help ?

Your date string is not valid.
Here is example of it:
String time = '2022-01-13';
DateTime parseDate = DateFormat("yyyy-MM-dd").parse(time); // to be date
var inputDate = DateTime.parse(parseDate.toString()); // to be string
var outputFormat = DateFormat('dd MMM yyyy'); // set format be for ex 13 Jan 2022
var outputDate = outputFormat.format(inputDate); // set to be a string

While it doesn't make much sense in this form, it will work:
import 'package:intl/intl.dart';
void main() {
String date = '12';
DateTime dateTime = DateFormat("MM").parse(date);
print(dateTime);
}

Related

Dart Flutter - How do I combine & convert separated date & time into one DateTime object

String oldDateStr = "2022-08-1";
String oldTimeStr = "03:10 pm";
DateTime? newDateTime; //2022-08-01 13:10 (yyyy-MM-dd HH:mm) <----- TARGET
final olddateFormat = DateFormat("yyyy-MM-d");
final newdateFormat = DateFormat("yyyy-MM-dd");
final oldtimeFormat = DateFormat("hh:mm a");
final timeFormatter = DateFormat("HH:mm");
DateTime oldTime12 = oldtimeFormat.parse(oldTimeStr.toUpperCase());
DateTime newTime24 = DateTime.parse(timeFormatter.format(oldTime12)); //This line is culprit in print() debug
DateTime oldDate = olddateFormat.parse(oldDateStr);
DateTime newDate = DateTime.parse(newdateFormat.format(oldDate));
I tried & combined various answers from SO posts but couldn't figure this out. So I'm posting the question by helplessness.
The accepted format is yyyy-MM-dd hh:mm aaa. am/pm marker assumes capital letters e.g PM.
import 'package:intl/intl.dart';
void main() {
String oldDateStr = "2022-08-1";
String oldTimeStr = "03:10 pm";
final result = DateFormat("yyyy-MM-dd hh:mm aaa").parse(
'$oldDateStr $oldTimeStr'.replaceAll('pm', 'PM').replaceAll('am', 'AM'),
);
print(result); // 2022-08-01 15:10:00.000
}
See DateFormat for more information.
You can get formatted date like this, make a function if you are using it frequently.
String oldDateStr = "2022-08-01";
String oldTimeStr = "03:10 pm";
DateTime? newDateTime;
String newDate = (oldDateStr + " "+oldTimeStr.substring(0, 5) + ":00.000");
DateFormat formatter = DateFormat ('yyyy-MM-dd hh:mm');
DateTime nt = DateTime.parse(newDate);
print(formatter.format(nt));
use this package to combine date and time and convert your datetime format to DateTime
String oldDateStr = "2022-08-1";
String oldTimeStr = "03:10 pm";
final String dateTimeString = oldDateStr+ " " + oldTimeStr;
final DateFormat format = new DateFormat("yyyy-MM-dd hh:mm a");
print (format.parse(dateTimeString));

flutter:: Is it possible to change the timezone of a datetime?

I want to represent the time the file was saved as a string. The time in my country is 9 hours ahead of utc time. How can I change the current utc time to 9 hours faster?
String _getTime({required String filePath}) {
String fromPath = filePath.substring(
filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('.'));
if (fromPath.startsWith("1", 0)) {
DateTime dateTime =
DateTime.fromMillisecondsSinceEpoch(int.parse(fromPath));
var dateLocal = dateTime.toLocal();
print(dateLocal);
print(dateTime);
int year = dateLocal.year;
int month = dateLocal.month;
int day = dateLocal.day;
int hour = dateLocal.hour;
int min = dateLocal.minute;
String dato = '$year-$month-$day--$hour:$min';
return dato;
} else {
return "No Date";
}
}
Use this package ---->>>>> https://pub.dev/packages/flutter_native_timezone
Add the package dependencies to your project, import the package into the file you're working in and write the code below to get your currenTimeZone
final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
debugPrint(currentTimeZone);

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
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
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();
}

Can't convert a Datetime from a string to another format (eg: 14/12/2021 03:34:03 PM to 03:34 pm)

I'am trying to convert a datetime string from one format to another. i tried to use intl package. But i don't know how to convert this string to another format.
The datetime string i'am getting from api is 14/12/2021 03:34:03 PM. I want to show it like this in my app (only time) 03:34 pm (Also want to make PM Small letter).
Try below code hope its helpful to you. I have tried it without using any third party library
String yourDate = '14/12/2021 03:34:03 PM';
DateFormat formateDate = DateFormat('dd/MM/yyyy hh:mm:ss a');
DateTime inputDate = formateDate.parse(yourDate);
String resultDate = DateFormat('hh:mm a').format(inputDate);
print(resultDate.toLowerCase());
Your Widget:
Text(
'Time : ${resultDate.toLowerCase()}',
style: TextStyle(
fontSize: 15,
),
),
Your Result Screen->
If you don't mind doing it the regexp way
import 'package:intl/intl.dart';
void main() {
var s = "14/12/2021 12:34:03 PM";
print(formatDateTimeString(s));
}
String formatDateTimeString(String s) {
RegExp regexp = RegExp("(AM|PM)");
// finds either AM or PM in string and converts it to lowercase
RegExpMatch match = regexp.firstMatch(s)!;
String end = match.group(0)!.toLowerCase();
// change datetime format to HH:mm as desired
DateTime dt = DateFormat("d/MM/yyyy HH:mm:ss").parse(s);
DateFormat newFormat = DateFormat("HH:mm");
String formattedS = newFormat.format(dt);
// append lowercase ampm
formattedS += " " + end;
return formattedS;
}
You can get it by using below,
dateFormat() {
String dateStart = '14/12/2021 03:34:03 PM';
DateFormat inputFormat = DateFormat("dd/MM/yyyy hh:mm:ss a");
DateTime input = inputFormat.parse(dateStart);
String dateOutput = DateFormat("hh:mm a").format(input);
return dateOutput.toLowerCase();
}
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
How to format DateTime in Flutter
please check out, it's for all formated datetime , you just pass your current and required date format
import 'package:intl/intl.dart';
void main() {
var data = "14/12/2021 03:34:03 PM";
print(getFormattedDateFromFormattedString(
value: data,
currentFormat: "yyyy/MM/dd HH:mm:ss a",
desiredFormat: "hh:mm a").toLowerCase()); //03:34 pm
}
String getFormattedDateFromFormattedString(
{required value,
required String currentFormat,
required String desiredFormat,
isUtc = false}) {
String formattedDate = "";
if (value != null || value.isNotEmpty) {
try {
DateTime dateTime =
DateFormat(currentFormat).parse(value, isUtc).toLocal();
formattedDate = DateFormat(desiredFormat).format(dateTime);
} catch (e) {
print("$e");
}
}
// print("Formatted date time: $formattedDate");
return formattedDate;
}

convent and find The difference between date time flutter

I need to help with my fluter code,
I have an API its response me a date as a String
{"time": "12/04/2020 16:09:33"}
and I get the current time in my code from the phone using
var now = new DateTime.now();
how I can calculate the difference between two date-time???
You can use the intl library.
import 'package:intl/intl.dart';
String formatDuration(Duration duration) {
return duration.toString().split('.').first.padLeft(8, '0');
}
final s = "12/04/2020 16:09:33";
final formatter = DateFormat('dd/MM/yyyy HH:mm:ss');
final dateTime = formatter.parse(s);
var now = DateTime.now();
var difference = now.difference(dateTime);
print(formatDuration(difference));
print result ex. 53:37:11
You can achieve that using difference() method which accepts date as DateTime object. Hence, first you need to convert your input date which is in String format, into DateTime. Working code below:
String date = "12/04/2020 16:09:33";
DateFormat dateFormat = DateFormat("yyyy/MM/dd HH:mm:ss");
DateTime dateTime = dateFormat.parse(date); // converts into Datetime
var nowDate = DateTime.now();
var difference = nowDate.difference(dateTime);
print(difference); // 17553602:53:49.047936