Convert string datetime to DateTime type in flutter [closed] - flutter

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to combine date and time to DateTime format. so that I can use it to send local notifications.
I am getting time and date separately from firebase as appointment_date and appointment_time:
using this code:
for (int i = 0; i < appt_list.length; i++) {
String name = appt_list[i].docName;
String k = appt_list[i].key;
Provider.of<NotificationService>(context, listen: false)
.sheduledNotification(datetime, name, k);
}
and i want to use custom (values stored in firebase for appointments reminder) timedate in local notification function like using 'scheduledNotificationDateTime' variable is doing:
Future sheduleddateNotification(DateTime datetime, String name, String key) async {
var scheduledNotificationDateTime = DateTime.now().add(Duration(seconds: 5));
var androidPlatformChannelSpecifics =
AndroidNotificationDetails(key,
'your other channel name', 'your other channel description');
var iOSPlatformChannelSpecifics =
IOSNotificationDetails();
NotificationDetails platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await _flutterLocalNotificationsPlugin.schedule(
0,
'Reminder Appointment',
'You have an appointment scheduled with $name at ${(time.hour)}:${(time.minute)}',
scheduledNotificationDateTime,
platformChannelSpecifics);
}
But I don't know how do I combine my date and time together and use them as one! Please help me out in solving this problem

How about something like this?
final String dateTimeString = appointment_date + " " + appointment_time;
final DateFormat format = new DateFormat("yyyy-MM-dd hh:mm a");
print (format.parse(dateTimeString));

Related

Google sheets- email based on date comparison for range of dates

I have two columns on my Google Sheet [Reminder] and [Reminder Date].
Reminder contains an email address to send a reminder to and the email should send out if Reminder Date is Today.
I've figured out the part of the code to send an email, that is not the problem. Here is what I have so far
var ss = SpreadsheetApp.getActive();
ss.setActiveSheet(spreadsheet.getSheetByName('Projects'), true);
var datesrg=ss.getRangeByName("Reminder Date");
var emailrg=ss.getRangeByName("Reminder");
var rdates=datesrg.getValues();
var remail=emailrg.getValues();
//in the for loop
var message = {
to: //Email,
subject: "Project Reminder",
body: "Hello, \n\nYou are receiving this email because you set a reminder for this project today.\n\nThank you,\n",
name: "Bot",
MailApp.sendEmail(message);
What I have in mind is a for loop that compares each date in rdates to today, and if it matches, gets the index value from rdates, fetches the corresponding index value for remail and then sets that as the email address for the email to be sent out to.
I'm struggling to use forEach and how to set the date to today for comparison. Help would be much appreciated.
It wasn't clear to me what you were attempting to do with the name. But here's the loop for comparing dates with todays date
function myfunction() {
var ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Projects")
var datesrg = ss.getRangeByName("Reminder Date");
var emailrg = ss.getRangeByName("Reminder");
var rdates = datesrg.getValues().flat();
var remail = emailrg.getValues().flat();
const dt = new Date();
const tdv = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()).valueOf();
rdates.forEach((d, i) => {
if (new Date(e).valueOf() >= tdv) {
MailApp.sendEmail(remail[i], "Project Reminder", "Hello, \n\nYou are receiving this email because you set a reminder for this project today.\n\nThank you,\n")
};
});
}
Assuming that datesrg has two columns, try this:
var dates = datesrg.getValues();
dates.forEach( row => {
if(row[0].getTime() === row[1].getTime()){
// put here what should be done when the condition is true
}
});
Related
Compare two dates with JavaScript

Comparing Dates in Google Scripts with Sheets Input

I am trying to create a pop up to warn a user they must update a part in inventory if the part date is more than 90 days old. The date on the sheet (Cell Q5) is autofilled from another sheet, but that shouldn't matter. The value for the cell on the spreadsheet is 9/2/2021. I've tried many things, but currently I am getting the value for Q5 showing up as NaN .
function CheckInvDate() {
var ss = SpreadsheetApp.getActive().getId();
var partsrange = Sheets.Spreadsheets.Values.get(ss, "BOM!A5:Q5");
var currentDate = new Date();
var parthist = new Date();
parthist.setDate(currentDate.getDate() -90);
for (var i = 0; i < partsrange.values.length; i++){
var name = partsrange.values [i][1]
var partdate = partsrange.values [i][16]
var parthisttime = new Date(parthist).getTime();
var partdatetime = new Date(partdate).getTime();
Logger.log("History " + parthisttime)
Logger.log("Current " + partdatetime)
SpreadsheetApp.flush()
// if (parthist > partdate == "TRUE") {
// SpreadsheetApp.getUi().alert('The price on '+ name + ' is out of date. Please update price and try again.')
// }
}
}
My last log was
[22-07-06 11:50:55:851 EDT] History 1649346655850
[22-07-06 11:50:55:853 EDT] Current NaN
I've seen a number of responses on Stack Overflow, but I can't understand them. They seem to refer to variables that I don't see in code, or commands I haven't seen before and I'm not sure if they are in date.
Try this:
function CheckInvDate() {
const ss = SpreadsheetApp.getActive();
const vs = Sheets.Spreadsheets.Values.get(ss.getId(), "BOM!A5:Q5").values;
let d = new Date();
d.setDate(d.getDate() - 90)
const dv = d.valueOf();
const oldthan5 = vs.map(r => {
if (new Date(r[16]).valueOf() < dv) {
return r;
}
}).filter(e => e);
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(`<textarea rows="12" cols="100">${JSON.stringify(oldthan5)}</textarea>`).setWidth(1000), "Older Than 90 Days");
}
This outputs a dialog with the rows older than 90 days
I went to try this on my script again after lunch, and for whatever reason I am no longer getting the NaN value. I made one change on the if statement to fix the logic, and now it is working correctly. Not sure what I did, but apparently the coding gods were unhappy with me before.
The only part I changed was
if (parthisttime > partdatetime) {
SpreadsheetApp.getUi().alert('The price on '+ name + ' is out of date. Please update price and try again.')
}

App Scripts stepping months and date formatting

I'm new to App Script, please be gentle!
I have a table with a start date and a number of months, I need to list each recurring month from the start date to the number of months.
I'm struggling with 2 issues:
The first date placed in the array seems to be updating as I cycle the dates
The formats are in UNIX and I can't get them to be useful despite an awful lot of reading!
Thank you so much for any help!
Input file (https://i.stack.imgur.com/2EJ65.png)
Output file(https://i.stack.imgur.com/0DH5R.png)
Console log (https://i.stack.imgur.com/NVqck.png)
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Get Data sheet
var rawData = ss.getSheetByName('Sheet3');
// Get a date and set it as a date format
var start = new Date(rawData.getRange("B2").getValues());
console.log(start);
// Get Months
var months = rawData.getRange("C2").getValues();
// Define dates array
var dates = [];
// Add first date
const startDate = start
dates.push([startDate]);
//Add rest of dates dates in a loop
for (var run = 1;run < months;run++) {
//get the last pasted month name
var lastMonth = start.getMonth();
//push next month
dates.push([start.setMonth(lastMonth+1)]);
}
// Get processedData sheet
var processedData = ss.getSheetByName('sheet2');
// Post the outputArray to the sheet in a single call
console.log(start);
console.log(startDate);
console.log(dates);
console.log(dates.length);
console.log(dates[0].length);
processedData.getRange(1,1,6,1).setValues(dates);
}
Incrementing Dates by month and setting format
function lfunko() {
const ss = SpreadsheetApp.getActive();
let dt = new Date();
let start = new Date(dt.getFullYear(),dt.getMonth(),dt.getDate());//need to change back to your value
const months = 10;//need to change back to your value
let dates = [];
dates.push([start]);
for (let run = 1; run < months; run++) {
dates.push([new Date(start.getFullYear(),start.getMonth() + run, start.getDate())])
}
ss.getSheetByName('Sheet0').getRange(1, 1, dates.length).setValues(dates).setNumberFormat("mm/dd/yyyy");//changed sheet name
Logger.log(dates);
}

flutter) how can I convert String to Time? [duplicate]

This question already has answers here:
How do I convert a date/time string to a DateTime object in Dart?
(8 answers)
unable to convert string date in Format yyyyMMddHHmmss to DateTime dart
(11 answers)
Closed last year.
Hi i have an array contains
List<dynamic> am = ['09:00', '09:30', '10:00', '10:30', '11:00', '11:30'];
and if they are selected
String time = '09:00'
how can I change time to the DateTime value or TimeOfDay
import 'package:intl/intl.dart';
if your time format is fixed (for example "hours:minutes" ) you can use this method
DateTime? _convertStringToDateTime(String time){
DateTime? _dateTime;
try{
_dateTime = DateFormat("hh:mm").parse(time);
}catch(e){}
return _dateTime;
}
You can use this:
TimeOfDay toTimeOfDay(String time){
List<String> timeSplit = time.split(":");
int hour = int.parse(timeSplit.first);
int minute = int.parse(timeSplit.last);
return TimeOfDay(hour: hour, minute: minute);
}
https://pub.dev/packages/date_format
See this package, By means of this package you can format your DateTime.

Want to compare two dates and take out the difference in days

I am getting Timestamp from Firebase Firestore and then formatting it into date and then want to take out the difference in days. And for that I am doing this:-
DateTime myDateTime = DateTime.parse(nameTimestamp!=null? nameTimestamp.toDate().toString() :DateTime.now().toString());
print('$myDateTime');
String formattedDateTime = DateFormat('yyyy,MM,dd').format(myDateTime);
print('$formattedDateTime');
final nameChangeDate = DateTime(2021,6,1);
final todayDate = DateTime.now();
final difference = todayDate.difference(nameChangeDate).inDays;
print(difference);
And now the problem I am facing is if I put formattedDateTime in front of nameChangeDate like mentioned below then at difference there's appear an error that The argument type 'String' can't be assigned to the parameter type 'DateTime'.
final nameChangeDate = formattedDateTime;
final todayDate = DateTime.now();
final difference = todayDate.difference(nameChangeDate).inDays; ///Error
print(difference);
Help me in this or guide me to take out the difference in some other way.