Flutter DateFormat Invalid date format - flutter

I have a string like this String dt = '04-09-2021 - 15:00'
i want to convert it into local time zone
and my code is:
if(dt != 'Not Available'){
return DateFormat('dd-MM-yyyy - HH:mm')
.format(DateTime.parse(dt).toLocal())
.toString();
}else{
return dt;
}
But i get the error: Invalid date format 04-09-2021 - 15:00

You should use parse, not format, the format functions receive a date, but you don't have a date, you have an string, use:
DateFormat('dd-MM-yyyy - HH:mm').parse(dt);

Here I wrote a dateformatter and convert it to local time. As well as you can format like as you wish.
// call getFormattedDateFromFormattedString function in Text
Center(
child: Text(getFormattedDateFromFormattedString(
currentFormat: "dd-MM-yyyy - HH:mm",
desiredFormat: "dd MMM yyyy HH:mm a",
value: "04-09-2000 - 15:00")),
)
// date fomatter function
String getFormattedDateFromFormattedString(
{#required String currentFormat,
#required String desiredFormat,
String value}) {
String formattedDate = "";
if (value != null || value.isNotEmpty) {
try {
DateTime dateTime = DateFormat(currentFormat).parse(value, true).toLocal();
formattedDate = DateFormat(desiredFormat).format(dateTime);
} catch (e) {
print("$e");
}
}
// print("Formatted date time: $formattedDate");
return formattedDate.toString();
}
Output:
N.B: My time zone GMT+6.0

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

How to convert a simple string to a DateTime object?

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

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

How to convert time stamp string from 24 hr format to 12 hr format in dart?

I am working on flutter application where i have to show time stamps but the response i got from api is in 24 hr format and i want to display time in 12 hr format in my application.
And i want to display on application in this format
Can you please help me regarding the easiest way of doing the formatting from 24 hr to 12 hr?
Dart intl framework helps you to format date/time into any type you want.
https://pub.dev/packages/intl
Especially for your case, you can use this code.
DateFormat("h:mma").format(date);
#Umair, as Sam pointed out, you can use intl package and can use jm() function without explicitly declaring the format like so,
For default DateTime
class MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Padding(
padding: EdgeInsets.all(20.0),
child: Center(
child: Text(new DateFormat.jm().format(DateTime.now()), style: TextStyle(fontSize: 18.0),),
)
)
));
}
}
Screenshot:
For 24 hr timestamp string
class MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
String timeStamp24HR = "2020-07-20T18:15:12";
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Padding(
padding: EdgeInsets.all(20.0),
child: Center(
child: Text(new DateFormat.jm().format(DateTime.parse(timeStamp24HR)), style: TextStyle(fontSize: 18.0),),
)
)
));
}
}
Screenshot:
More info on Flutter's parse method here - https://api.flutter.dev/flutter/dart-core/DateTime/parse.html
To convert UTC time to local time with the specified format including date
Import the below package:
package:intl/intl.dart';
Convert like below:
var dateFormat = DateFormat("dd-MM-yyyy hh:mm aa"); // you can change the format here
var utcDate = dateFormat.format(DateTime.parse(uTCTime)); // pass the UTC time here
var localDate = dateFormat.parse(utcDate, true).toLocal().toString();
String createdDate = dateFormat.format(DateTime.parse(localDate)); // you will get local time
You need to import import 'package:intl/intl.dart'; at the top of your file. Then DateFormat("h:mma") should do the trick.
Use Function from import 'package:intl/intl.dart'; library.
DateFormat.Hm().format(date);
it will give a 24 hours format time 23:30
DateTime now = DateTime.now();
String formattedDate = DateFormat().add_yMMMEd().add_jms().format(now);
O/p:Thu,jul 14,2022 4:50:24 PM
String utcTo12HourFormat(String bigTime) {
DateTime tempDate = DateFormat("hh:mm").parse(bigTime);
var dateFormat = DateFormat("h:mm a"); // you can change the format here
var utcDate = dateFormat.format(tempDate); // pass the UTC time here
var localDate = dateFormat.parse(utcDate, true).toLocal().toString();
String createdDate = dateFormat.format(DateTime.parse(localDate));
print("------------$createdDate");
return createdDate;
}
You can simply use TimeOfDay class:
var time = TimeOfDay.fromDateTime(DateTime.now());
print(time.hourOfPeriod);
print(time.minute);
print(time.period);
The below example shows how to get time from the picker and convert it using DateFormat("h:mm a"), here a denotes AM and PM
TimeOfDay? _selectedTime;
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay? timePicked = await showTimePicker(
context: context,
initialTime: TimeOfDay.now(),
);
if (timePicked != null)
setState(() {
_selectedTime = timePicked;
});
// Conversion logic starts here
DateTime tempDate = DateFormat("hh:mm").parse(
_selectedTime!.hour.toString() +
":" + _selectedTime!.minute.toString());
var dateFormat = DateFormat("h:mm a"); // you can change the format here
print(dateFormat.format(tempDate));
}
Output:
flutter: 8:00 PM
input: 23:43
var time = "12:00";
var temp = int.parse(time.split(':')[0]);
String? t;
if(temp >= 12 && temp <24){
t = " PM";
}
else{
t = " AM";
}
if (temp > 12) {
temp = temp - 12;
if (temp < 10) {
time = time.replaceRange(0, 2, "0$temp");
time += t;
} else {
time = time.replaceRange(0, 2, "$temp");
time += t;
}
} else if (temp == 00) {
time = time.replaceRange(0, 2, '12');
time += t;
}else{
time += t;
}
output: 11:43 PM
String time24to12Format(String time) {
int h = int.parse(time.split(":").first);
int m = int.parse(time.split(":").last.split(" ").first);
String send = "";
if (h > 12) {
var temp = h - 12;
send =
"0$temp:${m.toString().length == 1 ? "0" + m.toString() : m.toString()} " +
"PM";
} else {
send =
"$h:${m.toString().length == 1 ? "0" + m.toString() : m.toString()} " +
"AM";
}
return send;
}
Here are almost all the conversions of Date and time you can use in any Flutter app. This library will help you out in almost each format for date and time both import 'package:intl/intl.dart';
24hr -> 12 hr format:
var to12HrFormate = DateFormat("dd-MM-yyyy hh:mm aa")
.format(yourDateandTime) //if your datetime is in DateTime type use this method
var to12HrFormat = DateFormat("dd-MM-yyyy hh:mm aa")
.format(DateTime.parse(yourDateandTime)); //if your datetime is in String type use this method
if you only want to convert time only just change the format from DateFormat(dd-MM-yyyy hh:mm aa) to DateFormat(hh:mm aa)
12hr -> 24 hr format:
DateTime to24HrFormat= DateFormat("hh:mm a").parse(yourAMPMTime); // if you want type in DateTime
String to24HrFormat= DateFormat("hh:mm a").format(yourAMPMTime); //if you want the return type in String
here is a little explanation of Type Conversion in time
String -> DateTime:
static DateTime parseStringDate(String dateString,
{String format = 'yyyy-MM-d', bool localFromUTc = false}) {
if (dateString.isEmpty) return DateTime.now();
if (dateString.contains('am') || dateString.contains('pm')) {
dateString =
dateString.replaceFirst(' pm', ' PM').replaceFirst(' am', ' AM');
}
var date = DateFormat(format).parse(dateasString, localFromUTc).toLocal(); //for DateTime to String conversion use .format(dateasDateTime) in place of .parse()
return date;
}
Date In Format:
static String getDateInFormat(DateTime dateTime,
{String format = 'd/M/yyyy'}) {
return DateFormat(format).format(dateTime);
}
if you only want a single item from date like day, month or year
pass dd for day MMMM for month and yyyy in format in above function.