How to write code for getting that record By passing Date,MM,Year,HH,MM,SS
all these parameters are coming from DropdownList
public JsonResult Dif(int Day = 0, int Month=0, int Year=0, int HH, int MM, int Ss)
{
var x = (from n in db.Employees
where n.DataofBirth = (Day,Month,Year)
select n).First();
return new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
You need to create an instance of DateTime:
var date = new DateTime(Year, Month, Day, HH, MM, Ss);
var x = (from n in db.Employees
where n.DataofBirth = date
select n).First();
Also, it doesn't really make sense for the parameters to have a default value... especially if it's not a valid value! Neither the year, month or day can be 0.
Related
Our company offers soft loans to employees. I am trying to write some code that will set up a loan deduction schedule once a loan is approved. This is all done on google sheets. The schedule then can be linked to payroll etc.
The approved loans will appear in a format like this:-
Loans Approved - [Serial, Employee ID,Amount, Monthly Deductions,Requested Date,Deduction Start Date]
I am looking to build an array that will have the first 4 elements that repeat and the deduction month to increase by 1
So far this is my code
function myFunction() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Loans");
var range = sheet.getDataRange();
var data = range.getValues()
var lastRow = range.getLastRow()
var scheduleSheet = ss.getSheetByName("Schedule")
var scheuduleLastRow = scheduleSheet.getDataRange().getLastRow;
for(let i=1;i<lastRow;i++){
var serial = data [i][0]
var id = data [i][1]
var amount = data[i][2]
var monthlyRepayment = data [i][3]
var startDate = new Date (data [i][5])
var markScheduleDone = sheet.getRange(i+1,7)
var fullMonths = Math.floor(amount/monthlyRepayment)
var remainderMonth = (amount/monthlyRepayment)-fullMonths
var remainderAmount = Math.round(remainderMonth*monthlyRepayment)
for (let j=1;j<=fullMonths+1;j++){
var incrementalMonths = new Date(startDate.setMonth(startDate.getMonth()+1)) ;
}
var newArray = [serial,id,monthlyRepayment];
var remainderArray = [serial,id,remainderAmount];
var reptArray = Array(fullMonths).fill(newArray);
var finalArray = [...reptArray,remainderArray]
Logger.log(finalArray)
var toPasteto = scheduleSheet.getRange(scheuduleLastRow+1,1,finalArray.length,3)
toPasteto.setValues(finalArray)
markScheduleDone.setValue ("Done")
}
}
I am close but I cant figure out how to join the incrementalMonths to the finalarray.
This is the first time im using a loop within a loop
Also any guidance if I could have done this better?
Kinldy requesting some guidance
I'm not sure if this is exactly what you are looking for but try this.
Notice I fill the array finalArray with all the newArrays so I only have to setValues() once. Same with markDone.
I increment the month but if the day happens to fall outside the number of days in a month it will increment to another day. So for any 28 or 30 day months there should be another check but I didn't do that.
My particular style of coding is to always use a try {} catch() {} block, always terminate a line with semicolon ;, and to use let instead of var whenever possible.
function myFunction() {
try {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Loans");
var range = sheet.getDataRange();
var data = range.getValues()
var lastRow = range.getLastRow()
var scheduleSheet = ss.getSheetByName("Schedule")
var scheuduleLastRow = scheduleSheet.getDataRange().getLastRow();
let finalArray = [];
let markDone = [];
for(let i=1;i<lastRow;i++){
var serial = data [i][0];
var id = data [i][1];
var amount = data[i][2];
var monthlyRepayment = data [i][3];
var startDate = new Date (data [i][5]);
var fullMonths = Math.floor(amount/monthlyRepayment);
var remainderMonth = (amount/monthlyRepayment)-fullMonths;
var remainderAmount = Math.round(remainderMonth*monthlyRepayment);
let day = startDate.getDate();
if( day > 28 ) throw "This function has not adjusted for short months"
let month = startDate.getMonth();
let year = startDate.getFullYear();
let newArray = [];
for (let j=1;j<=fullMonths+1;j++){
month++;
if( month > 11 ) {
month = 0;
year++;
}
var date = new Date(year,month,day);
newArray.push([serial,id,monthlyRepayment,date])
}
newArray.push([serial,id,remainderAmount,date]);
finalArray = finalArray.concat(newArray);
Logger.log(newArray);
markDone.push(["Done"]);
}
sheet.getRange(2,7,markDone.length,1).setValues(markDone);
scheduleSheet.getRange(scheuduleLastRow+1,1,finalArray.length,4).setValues(finalArray);
}
catch(err) {
Logger.log(err)
}
}
I'm working on a flutter app, one of its features is to add your drug dose timings to get a reminder to take your drug. and I need to sort the timings to get the 'next_dose' to appear here :
https://drive.google.com/file/d/1j5KrRbDj0J28_FrMKy7dazk4m9dw202d/view?usp=sharing
this is an example of the list which I want to sort
[8:30 AM, 3:30 PM, 9:30 AM, 7:00 AM]
function I made to get the greater between 2 timings
int greater(String element,String element2){
var hour = element.toString().split(':')[0];
var hour2 = element2.toString().split(':')[0];
var minute = element.toString().split(':')[1].split(' ')[0];
var minute2 = element2.toString().split(':')[1].split(' ')[0];
var day = element.toString().split(':')[1].split(' ')[1];
var day2 = element2.toString().split(':')[1].split(' ')[1];
if(day == 'AM' && day2 == 'PM')
return -1;
else if(day2 == 'AM' && day == 'PM')
return 1;
else if(day == day2)
{
if(int.parse(hour) > int.parse(hour2)) return -1;
else if(int.parse(hour) < int.parse(hour2)) return 1;
else{
if(int.parse(minute) > int.parse(minute2))
return 1;
else
return -1;
}
}
here I tried to use the function to sort the list'Dose'
dose.sort((a,b)=>greater(a,b));
Instead of creating a sort callback with a lot of complicated logic, it'd be simpler if the callback parsed the time strings either into an int or into a DateTime object and compared those. For example:
/// Parses a time of the form 'hh:mm AM' or 'hh:mm PM' to a 24-hour
/// time represented as an int.
///
/// For example, parses '3:30 PM' as 1530.
int parseTime(String time) {
var components = time.split(RegExp('[: ]'));
if (components.length != 3) {
throw FormatException('Time not in the expected format: $time');
}
var hours = int.parse(components[0]);
var minutes = int.parse(components[1]);
var period = components[2].toUpperCase();
if (hours < 1 || hours > 12 || minutes < 0 || minutes > 59) {
throw FormatException('Time not in the expected format: $time');
}
if (hours == 12) {
hours = 0;
}
if (period == 'PM') {
hours += 12;
}
return hours * 100 + minutes;
}
void main() {
var list = ['8:30 AM', '3:30 PM', '9:30 AM', '7:00 AM'];
list.sort((a, b) => parseTime(a).compareTo(parseTime(b)));
print(list); // Prints: [7:00 AM, 8:30 AM, 9:30 AM, 3:30 PM]
}
Alternatively, you can use package:intl and DateFormat.parse to easily parse strings into DateTime objects.
Here we get the time slot by passing the start and end time duration.
List<String> createTimeSlot(
Duration startTime, Duration endTime, BuildContext context,
{Duration step = const Duration(minutes: 30)} // Gap between interval
) {
var timeSlot = <String>[];
var hourStartTime = startTime.inHours;
var minuteStartTime = startTime.inMinutes.remainder(60);
var hourEndTime = endTime.inHours;
var minuteEndTime = endTime.inMinutes.remainder(60);
do {
timeSlot.add(TimeOfDay(hour: hourStartTime, minute: minuteStartTime)
.format(context));
minuteStartTime += step.inMinutes;
while (minuteStartTime >= 60) {
minuteStartTime -= 60;
hourStartTime++;
}
} while (hourStartTime < hourEndTime ||
(hourStartTime == hourEndTime && minuteStartTime <= minuteEndTime));
debugPrint("Number of slot $timeSlot");
return timeSlot;
}
Function call
createTimeSlot(Duration(hours: 1, minutes: 30),
Duration(hours: 3, minutes: 30), context);
Output:
Number of slot [1:30 AM, 2:00 AM, 2:30 AM, 3:00 AM, 3:30 AM]
Requirement : Select list of records from table for members whose ID and First name matches with records.
The number of members in the request may vary as per the request:
I have written following code to generate dynamic query using expressions.
private Expression<Func<TmpOncMemberAuth, bool>> CreateQueryExpression(List<MemberRequest> memberRequests)
{
var type = typeof(TmpOncMemberAuth);
// member =>
var memberParam = Expression.Parameter(type, "member");
var requests = memberRequests;
Expression selectLeft = null;
Expression filterExpression = null;
foreach (var member in requests)
{
var comparison = BuildSubQuery(member, memberParam, type);
if (selectLeft == null)
{
selectLeft = comparison;
filterExpression = selectLeft;
continue;
}
filterExpression =
Expression.Or(filterExpression, comparison);
}
return Expression.Lambda<Func<TmpOncMemberAuth, bool>>
(filterExpression, memberParam);
}
private Expression BuildSubQuery(MemberRequest member, ParameterExpression memberParam, Type type)
{
// LHS
// member.MemberID
Expression leftMemberID = Expression.Property(memberParam, type.GetProperty("MemberId"));
Expression leftMemberFirstName = Expression.Property(memberParam, type.GetProperty("MemberFirstName"));
// RHS
Expression requestMemberID = Expression.Constant(member.MemberID);
Expression requestFirstName = Expression.Constant(member.FirstName);
// member.MemberID == requestMemberID
Expression compareID =
Expression.Equal(leftMemberID, requestMemberID);
Expression compareFName =
Expression.Equal(leftMemberFirstName, requestFirstName);
// condition for a member
Expression comparison = Expression.AndAlso(compareID, compareFName);
return comparison;
}
// query call in the main
var whereQuery = CreateQueryExpression(memberData);
var memberAuthData = await FindAllAsyncFromTemp(whereQuery);
This generate a SQL query in the below format, which take a lot time
SELECT [#].[CaseID] AS [CaseId], [#].[MemberID] AS [MemberId], [#].[MemberFirstName], [#].[MemberLastName], [#].[MemberDOB]
FROM [#ONCMemberAuth] AS [#]
WHERE ((CASE
WHEN (([#].[MemberID] = '12345') AND ([#].[MemberFirstName] = 'James') ) THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END | CASE
WHEN (([#].[MemberID] = '6789') AND ([#].[MemberFirstName] = 'WILLERS') ) THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END)
) = CAST(1 AS bit)
I need to create SQL query like below which executes faster than the above one
SELECT [#].[CaseID] AS [CaseId], [#].[MemberID] AS [MemberId], [#].[MemberFirstName], [#].[MemberLastName], [#].[MemberDOB]
FROM [#ONCMemberAuth] AS [#]
WHERE ((([#].[MemberID] = '1234') AND ([#].[MemberFirstName] = 'James')) OR (([#].[MemberID] = '56789') AND ([#].[MemberFirstName] = 'WILLERS') ) )
I have an appointment management scenario in which I have a field List of availableWeekDays of a person on which weekdays they are available for booking. For example if they are available on monday I have a value in availableWeekDays list as 1.
I have currentDate stored in a DateTime variable using DateTime.now().
What I have to do is first look if today's week day matches the availableWeekDay of person. If yes then bookingDate is valid else I have to look for nearest future date with weekday of person. I have tried following solution but it works for one week day as I'm using first index.
void main() {
DateTime bookingDate = DateTime.now();
int availableWeekDays = [1,4,7];
getDate(){
if(bookingDate.weekday == availableWeekDays[0]){
print("Available on $bookingDate ");
} else {
bookingDate = bookingDate.add(Duration(days: 1));
getDate();
}
}
getDate();
}
I want to find the nearest future date among all weekdays present in list.
DateTime findNearestWeekday(List<int> availableWeekdays) {
assert(availableWeekdays.isNotEmpty);
var date = DateTime.now();
final weekday = date.weekday;
for (var num in availableWeekdays) {
if (num == date.weekday) {
return date;
} else if (date.weekday < num) {
return date.add(Duration(days: num - weekday));
}
}
/// I have assumed that you will always have a sorted list of available
/// weekdays, in case you do not have a sorted list, either you can sort
/// the list first or just use this line (instead of the last one),
///
/// ```dart
/// import 'dart:math'; /// Add on Top of file.
///
/// return date.add(Duration(days: 7 - weekday + availableWeekdays.reduce(min)))
/// ```
///
/// I will prefer to pre sort the array before storing it somewhere,
/// because it will add an additional dependency dart:math
return date.add(Duration(days: 7 - weekday + availableWeekdays[0]));
}
A more efficient solution would be:
DateTime getDate() {
var currentDay = bookingDate.weekday;
var offset = (availableWeekDay - currentDay).remainder(7);
return offset == 0 ? bookingDate : bookingDate.add(Duration(days: offset));
}
Do be aware that adding "days" (multiples of 24 hours) to a date may run into daylight savings issues if the time of the bookingDate is close to midnight.
I forgot to reassign the result to the variable. This works now.
void main() {
DateTime bookingDate = DateTime.now();
int availableWeekDay = 1;
getDate(){
if(bookingDate.weekday == availableWeekDay){
print("Available on $bookingDate ");
} else {
bookingDate = bookingDate.add(Duration(days: 1));
getDate();
}
}
getDate();
}
I am looking for logic which can add couple of days to a custom date(not current date)
Below is Correlation function:
web_reg_save_param("Recommended_Date",
"LB=\"start\":\"",
"RB/DIG=T##:##:##\",",
"Ord=1",
"Search=Body",
LAST);
I want to add +21 days to Recommended_Date parameter. I tried doing below thing but no luck
lr_save_datetime("%Y-%M-%D", lr_eval_string("{Recommended_Date}") + (ONE_DAY*21), "New_Date");
Can anyone please assist me.
One of our engineers prepared this example for you:
int diff_days(char * dateString, char * dateFormat) {
int year, month, day;
struct tm info;
double delta;
double days=0;
time_t today;
time(&today);
sscanf(dateString, dateFormat, &year, &month, &day);
info.tm_year = year - 1900;
info.tm_mon = month - 1;
info.tm_mday = day;
// info.tm_hour = 0;
// info.tm_min = 0;
// info.tm_sec = 0;
info.tm_isdst = -1;
mktime(&info);
delta = difftime(mktime(&info),today);
if (delta >= 0) {
days = difftime(mktime(&info),today)/ 86400.0 +1;
} else {
days = difftime(mktime(&info),today)/ 86400.0;
}
return (int)days;
}
Action()
{
int plus;
lr_save_string("2020-09-01","D2");
plus = diff_days(lr_eval_string("{D2}"),"%d-%d-%d");
lr_save_datetime("%Y-%m-%d", DATE_NOW + ONE_DAY*(21+plus), "New_Date");
lr_save_string("2020/04/05","D2");
plus = diff_days(lr_eval_string("{D2}"),"%d/%d/%d");
lr_save_datetime("%Y/%m/%d", DATE_NOW + ONE_DAY*(21+plus), "New_Date");
return 0;
}