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
Related
I want to create a function which does not allow the user to remove the appointment once the timestamp for the appointment has past already. But what i tried below does not work, i hope to get some guidance from you guys
My widget.filter is a var which has the timestamp value from firebase
DateTime currentPhoneDate = DateTime.now(); //DateTime
Timestamp myTimeStamp = Timestamp.fromDate(currentPhoneDate); //To TimeStamp
DateTime myDateTime = myTimeStamp.toDate(); // TimeStamp to DateTime
print("current phone data is: $currentPhoneDate");
print("current phone data is: $myDateTime");
if(myTimeStamp < widget.filter){
print('work');
}else{
print('fail');
}
DateTime currentPhoneDate = DateTime.now();
Timestamp myTimeStamp = Timestamp.fromDate(currentPhoneDate);
DateTime myDateTime = myTimeStamp.toDate();
print("myTimeStamp is: $myTimeStamp");
print("currentPhoneDate is: $currentPhoneDate");
print("myDateTime is: $myDateTime");
// if widget.filter DataType is not Timestamp then first convert it to Timestamp.
if (myTimeStamp.millisecondsSinceEpoch <
widget.filter.millisecondsSinceEpoch) {
print('work');
} else {
print('fail');
}
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));
i have fetched data from an api which contains employees working time,
i want to calculate total working hours each day
here's how i get the data from the api for 1 single day
Future<List> getPunchData(String empCode, DateTime date) async {
String ip = await confObj.readIp();
DateTime end = new DateTime(date.year, date.month, date.day, 23,59,59);
final response = await http.get(Uri.parse("url/$empCode&$date&$end" ));
final String t = response.body;
var jsonData =jsonDecode(t);
return jsonData;
}
the api result is this:
{
"id": 10,
"punch_time": "2022-03-08 13:30:19.000000",
},
{
"id": 11,
"punch_time": "2022-03-08 16:22:39.000000",
}..
..
..
how can i automatically calculate and isplay total hours when after the widget is loaded
You can use the parse function of the DateTime object to convert the String date into DateTime.
The code would somewhat look like this (can't say for sure as I don't know your API):
final DateTime startTime = DateTime.parse(jsonData[0]['punch_time']);
final DateTime endTime = DateTime.parse(jsonData[1]['punch_time']);
Once you have the DateTime object, you can use the difference function to get a Duration object which will tell you the hours an employee has worked.
final Duration durationWorked = startTime.difference(endTime);
final int hoursWorked = durationWorked.inHours;
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);
}
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;
}