Date comparision on cshtml view - asp.net-mvc-4

I am using the below code to compare 2 dates on cshtml view with knockout binding.
data-bind="visible: (new Date(appointmentDate) - new Date() < 0) && isStart()"
It is working fine but that is including time as well while comparing. I don't want to include time in comparision only date.

I quick search on google pointed me to Formatting Date in Knockout Template this will allow us to get the date and compare it. Looking like
data-bind="visible: (
moment(new Date(appointmentDate)).format('MM/DD/YYYY') -
moment(new Date()) < 0) && isStart()"
I didn't try just let me know if works
Also momento allows you to calculate difference of dates
var dateB = moment('2014-11-11');
var dateC = moment('2014-10-11');
console.log('Difference is ', dateB.diff(dateC), 'milliseconds');
console.log('Difference is ', dateB.diff(dateC, 'days'), 'days');
console.log('Difference is ', dateB.diff(dateC, 'months'), 'months');
So basically we would do
data-bind="visible: (
moment(new Date(appointmentDate)).format('MM/DD/YYYY').diff(new Date().format('MM/DD/YYYY'),'days') < 0) && isStart()"

Related

Vuejs update a value used with v-for dynamically

So I'm making an attendance tracker with Vuejs and Vuetify, and I want it to look like this:
A Calender made up of v-card components, and a list of absences read in from a database. I have my API set up and am able to retrieve a list of absences without any issues, but when it comes to putting them on the screen I have some issues. What I want to do is this:
The user selects the month and year. Each card then shows one day of this month. I have a function called getAbsDate(date) that returns a list of absences for the date passed to it. I want it to work something like this in each card:
<v-card min-height="170" tile>
<v-card-text class="text-center black--text">
{{i}}
<v-sheet
color="blue"
class="pa-1"
v-for="abs in getAbsDate(i+'.'+monthsNums[selMonth]+'.'+selYear)"
:key="abs['id']"
>{{abs["name"]}}</v-sheet>
</v-card-text>
</v-card>
selMonth is the month the user selected, and selYear is the year the user selected. This doesn't work however. I don't get any errors, the cards are just empty. getAbsDate() returns a list of objects. Any ideas as to why this doesn't work?
Thanks!
EDIT
Here is the declaration of my getAbsDate() function.
getAbsDate: function(date) {
let l = [];
this.absences.forEach(abs => {
if (abs["start"] == date) {
l.push(abs);
}
if (abs["end"] == date) {
l.push(abs);
}
let day_start = moment(abs["start"].replace(".", "/"), "DD/MM/YYYY")
.toDate()
.getTime();
let day_end = moment(abs["end"].replace(".", "/"), "DD/MM/YYYY")
.toDate()
.getTime();
let day_date = moment(date.replace(".", "/"), "DD/MM/YYYY")
.toDate()
.getTime();
if (day_start <= day_date && day_date <= day_end) {
l.push(abs);
}
});
return l;
}
}
The formatting is not quite right at the .toDate() and the .getTime(), but in my file it is, s it is not the issue.

Why is my 'WHERE' clause based on a 'DATE' failing?

I'm using node.js to connect to an SQL database (SQL Server 2016 specifically). My table, called transactionCounts, has the following tables and data types:
staff_id: varchar(50), date: Date, count: int;
The 'date' field is just a date, not a DateTime, for clarity. Records look like this: "2017-08-07"
I'm using the mssql package, const sql = require('mssql');
So basically, I have a function which accepts a start date and an end date and does this with them:
function(start, end) {
let ps = new sql.PreparedStatement(transactionRegisterSqlPool);
ps.input('start', sql.Date);
ps.input('end', sql.Date);
ps.prepare('SELECT staff_id, SUM(Count) TotalCount FROM [TransactionRegister].[dbo].[transactionCounts] ' +
'WHERE date >= #start AND date < #end GROUP BY staff_id', err => {
.execute({start: start, end: end}, (err, result) => {});
});
};
I've simplified the function for illustrations sake (it normally returns a promise), but here's what's going wrong:
I pass in the dates of Aug 20 midnight, and Aug 27 midnight, and what I'm expecting to get back is the sum for the dates 20,21,22,23,24,25 and 26 naturally (7 days, a week).
26th isn't being included though (definitely), and I'm not entirely sure but I'd wager that the 19th is being included. I think it's a daylight-savings issue, because these dates, when i call .toISOString(), look like 2017-08-19T23:00:00.000Z and 2017-08-26T23:00:00.000Z respectively (11pm the night prior).
I've modified my function to use strings instead of dates, and this seems to work and returns the correct Sums:
function(start, end) {
let ps = new sql.PreparedStatement(transactionRegisterSqlPool);
ps.input('start', sql.VarChar);
ps.input('end', sql.VarChar);
start = `${start.getFullYear()}/${start.getMonth() + 1}/${start.getDate()}`;
end = `${end.getFullYear()}/${end.getMonth() + 1}/${end.getDate()}`;
ps.prepare('SELECT staff_id, SUM(Count) TotalCount FROM [TransactionRegister].[dbo].[transactionCounts] ' +
'WHERE date >= #start AND date < #end GROUP BY staff_id', err => {
ps.execute({start: start, end: end}, (err, result) => {});
});
};
But it seems...wrong to take my dates and turn them into strings to work my way around this issue. What is the correct way to deal with dates between Javascript Dates and SQL Dates, so that this apparent Daylight-Savings-caused issue is avoided?
Your problem is that JavaScript does not have a "date" type, only "datetime", yet SQL does have a "date" type. Because of that, you will have to do the conversion.
If you wrap it in a function, it is still readable:
function toDateString(d) {
return `${d.getFullYear()}/${d.getMonth() + 1}/${d.getDate()}`;
}
ps.prepare('SELECT staff_id, SUM(Count) TotalCount FROM [TransactionRegister].[dbo].[transactionCounts] ' +
'WHERE date >= #start AND date < #end GROUP BY staff_id', err => {
ps.execute({start: toDateString(start), end: toDateString(end)}, (err, result) => {});
});

SQL to Linq group by count

I have a single column in a table to count specific rows. The sql query is as below:
SELECT
CASE
WHEN trail LIKE 'ClassA%' THEN 'ClassA'
WHEN trail LIKE 'ClassB%' THEN 'ClassB'
WHEN trail LIKE 'SemA%' THEN 'SemesterA'
WHEN trail LIKE 'SemB%' THEN 'SemesterB'
END AS Logs
, COUNT(*) AS Count
FROM Logs where s_date >= 'from date from UI' and e_date <= 'to date from ui'
GROUP BY
CASE
WHEN trail LIKE 'ClassA%' THEN 'ClassA'
WHEN trail LIKE 'ClassB%' THEN 'ClassB'
WHEN trail LIKE 'SemA%' THEN 'SemesterA'
WHEN trail LIKE 'SemB%' THEN 'SemesterB'
END
The above query result in sql fine as
ClassA 20
ClassB 5
SemesterA 2
SemesterB 50
Now, I need to change this sql to Linq with a date filter (from date, to date).
Please suggest change in query to simplyfy it.
Thanks
Tried:-
var data = _db.Logs.Where(p => p.trail.StartsWith("ClassA") && (p.SDate.Date >= CDate.Date && p.SDate.Date <= FDate.Date)).GroupBy(p => p.trail.StartsWith("ClassA")).Select(s =>
new
{
source = "Class - A total",
percentage = s.Count()
}).Union(_db.Logs.Where(p => p.trail.StartsWith("ClassB") && (p.SDate.Date >= CDate.Date && p.SDate.Date <= FDate.Date)).GroupBy(p => p.trail.StartsWith("ClassB")).Select(s =>
new
{
source = "Class - B total",
percentage = s.Count()
}).Union(_db.Logs.Where(p => p.trail.StartsWith("SemesterA") && (p.SDate.Date >= CDate.Date && p.SDate.Date <= FDate.Date)).GroupBy(p => p.trail.StartsWith("SemesterA")).Select(s =>
new
{
source = "Semester - A total",
percentage = s.Count()
}).Union(_db.Logs.Where(p => p.trail.StartsWith("SemesterB") && (p.SDate.Date >= CDate.Date && p.SDate.Date <= FDate.Date)).GroupBy(p => p.trail.StartsWith("SemesterB")).Select(s =>
new
{
source = "Semester - B total",
percentage = s.Count()
})))).ToList();
Try storing all the interesting starting keys in an enumerable of some sort and then using the built in group by method overload which outputs a result mapped from the key,group pairs (c.f. https://msdn.microsoft.com/en-us/library/vstudio/bb549393(v=vs.100).aspx)
string[] startingKeys = new string[] {"ClassA","ClassB","SemsterA","SemesterB"};
var data =_db.Logs.Where(p=>(p.SDate.Date >= CDate.Date && p.SDate.Date <= FDate.Date)&&startingKeys.Any(k=>p.Logs.StartsWith(k))).GroupBy(p=>startingKeys.Where(k=>p.Logs.StartsWith(k)).First(),(key,items)=>new {source=key,count = items.Count()})
One advantage of this method is you can change the starting keys at runtime if you feel like it.

LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method

Hello This is my first post here
I'm facing some issue with EF , I have tried the following code in VS 2010 with EF 5 and 6.
I have table called MYTABLE and field ReveivedTime which varchar(255) but this has Datetime values like "4/29/2014 12:00:00 AM".
Note : I can not change the DataType and I can not write SP to Convert , I do have limitations, So I do have option to work with LAMBDA
I have tired the following code in LINQPad 4 itis working fine but the same is not working in VS2010 with EF 5/6.
getting error
LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression.
Convert.ToDateTime(si.ReceivedTime) is causing the problem
MYTable
.Where (
si =>
((Convert.ToDateTime(si.ReceivedTime) >= DateTime.Now.AddDays(-10)) &&
(Convert.ToDateTime (si.ReceivedTime) <= DateTime.Now)
)
)
.GroupBy (g => new
{
Day = Convert.ToDateTime(g.ReceivedTime).Day,
Month = Convert.ToDateTime(g.ReceivedTime).Month,
Year = Convert.ToDateTime(g.ReceivedTime).Year,
City = g.City,
})
.Select (
g =>
new
{
Count = g.Count(),
g.Key.Day,
g.Key.Month,
g.Key.Year,
g.Key.City,
Date = Convert.ToDateTime(g.Key.Year + "/" + g.Key.Month + "/" + g.Key.Day),
}
)
.OrderBy(x => x.Count)
Really appreciate your solution and advanced thanks too.
Instead of Convert.ToDateTime (si.ReceivedTime) <= DateTime.Now try SqlFunctions.DateDiff("s", si.ReceivedTime, DateTime.Now) > 0

Html5 type date - need full date value in database

it is my html code
<div class="required" id="join_form">
<label for="DOB">DateOfBirth:</label>
<input type="date" name="date" id="date" required pattern="(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d" aria-required="true" aria-describedby="age-format" max="2004-12-31" min="1940-12-31" />
<span id="age-format" class="help" align="center">Format: mm/dd/yyyy, mm-dd-yyyy, mm.dd.yyyy, mm dd yyyy</span>
</div>
javascript to validate this type=date in other browsers
var mydate = document.getElementById('date'),
mydateError = document.getElementById('age-format');
mydate.addEventListener('input', function() {
if (!mydate.value.match(/\d{4}-\d{1,2}-\d{1,2}/)) {
mydateError.innerHTML = 'Please specify a valid date in the form 1940-2004 ';
mydateError.style.display = 'inline-block;font-size:6pt;text-align:center;';
} else {
var value = new Date(date.value),
min = new Date(date.min),
max = new Date(date.max);
if (value < min || value > max) {
mydateError.innerHTML = 'Date has to be between ' + min.toDateString() + ' and ' + max.toDateString();
mydateError.style.display = 'inline-block';
} else {
mydateError.style.display = 'none';
}
}
});
php validation and insert for date
$DOB=mysql_real_escape_string($_POST['date']);
$sql="INSERT INTO register(DOB) VALUES("$DOB");
i want to get whole date of birth like mm/dd/year but in my database i am only getting year like 1970 or 1987 like that....i cant figure out where i got wrong
PHP mysql insert date format
This Link did help me I used this to validate and insert type="date" in database
$timestamp = strtotime($DOB);
$date = date('d-m-y', $timestamp);
$sql="INSERT INTO register(DOB) VALUES(FROM_UNIXTIME($timestamp))";
and my other Mistake was to set DOB as int in database
Data type required in a mysql for a date containing day-month-year
it should be DATE or DATETYPE
#Tonywilk Thankx :D