Get Date part of DateTime(ASP.NET MVC) - javascript

I have this property in Model
[Display(Name = "День рождения")]
[DataType(DataType.Date)]
public System.DateTime Birthday { get; set; }
And write to database value like this via AJAX
<script>
$(document).ready(function () {
$('#save').click(function () {
save();
});
});
function save() {
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
FIO: $('#FIO').val(),
Email: $('#Email').val(),
Salary: $('#Salary').val(),
Telephone: $('#Telephone').val(),
English: $('#english').val(),
City: $('#City').val(),
Birthday: $('#Birthday').val(),
id: $('#Interview_Id').val(),
},
url: '#Url.Action("WelcomeWriter", "Interwier")',
success: function (da) {
if (da.Result === "Success") {
window.location.href = da.RedirectUrl;
} else {
alert('Error' + da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
But my problem is this - it is writing Date and Time , I only need Date.
How I can fix this?

You can use this:
var date = new Date($('#Birthday').val());
This will give you access to all the Date functions.
For example:
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear()
So for full date:
var fullDate=day+"/"+month+"/"+year;
Or:
var fullDate=d.toLocaleDateString();

Format your date in your save() method before you do your ajax call. Something like this:
var d = new Date($('#Birthday').val());
var birthday = d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2)
+ "-" + ('0' + d.getDate()).slice(-2);

Related

Update a value on a entry on the table - issue

I have these columns on my table:
CardNumber
DateRegister
TimeRegister
DateExit
TimeExit
I read a value that is in a box, and when I press enter, the
Cardnumber, DateRegister,TimeRegister is add to the SQL Database
So I'll have like
CardNumber|DateRegister|TimeRegister|DateExit|TimeExit
124455|23-10-2022|11:00|null|null|
My Issue is, If I read the same card again, before I need to see if there is already one entrance on database with that card number, that don't have still DateExit and TimeExit.
If dont, I need to update that line, with that information, of if is a new one, will add a new entrance on the database
This is my code:
#section readcard{
<script>
$(function () {
$("#readONchange").change(function () {
var param1 = new Date();
var param2 = param1.getDate() + '/' + (param1.getMonth() + 1) + '/' + param1.getFullYear();
var param3 = param1.getHours() + ':' + param1.getMinutes() + ':' + param1.getSeconds();
var es = {};
/*es.IdCartao = $("#readONchange").val();*/
/*es.DateRegister = param2;*/
//Le cartao / Le data / Le Hora
es.IdCartao = $("#readONchange").val();
es.DateRegister = param2;
es.TimeRegister = param3;
if (es.IdCartao != null)
{
} else if (es.IdCartao == null) {
empregados.IdCartao = es.IdCartao(id);
(es.IdCartao == $("#readONchange").val && es.DateRegister != null && es.TimeRegister != null)
es.TimeExit = param3;
alert(es.IdCartao == $("#readONchange").val);
} else {
alert("erro")
}
alert("Register ADD!")
$.ajax({
type: "POST",
url: '#Url.Action("AddReport")',
data: '{es: ' + JSON.stringify(es) + '}',
dataType: 'json',
contentType: "application/json; charset=utf-8",
sucess: function () {
alert("Data Insert with Sucess");
},
error: function () {
alert("ERROR! on the regist");
}
});
});
});
</script>

javascript - how to create countdown to date and time from sql server database?

It's my first time using a countdown in javascript so I have researched a little about this topic and I found some interesting links: "how to countdown to a date" and "https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/", but my question is if I want to get data and time from the database, how can I do that? E.g.: I have a table Event with ID,Event,StartDate,StartTime and EndTime. How can I change from this: "var end = new Date('02/19/2012 10:1 AM');" from the first link or this: "Schedule the Clock Automatically" from the second to countdown time until event with the most recent time and date, and so on. Please keep in mind that I'm a total nooby so please bear with me. Sorry for any misspelling. Thank you!
Update:
This is the controller part: [HttpGet]
public JsonResult GetEvent(int Id)
{
BOL1.IMS2Entities db = new BOL1.IMS2Entities();
var ev = from e in db.tbl_Event
where e.ID == Id
select e;
//return Json(ev.FirstOrDefault(), JsonRequestBehavior.AllowGet);
return Json(Id, JsonRequestBehavior.AllowGet);
}
and this is the scripting part:
<script>
function GetEvent() {
debugger;
$.ajax({
type: "GET",
url: "Home/GetEvent",
data: { Id: ID },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('error');
}
});
}
var tbl_Event.StartDate = 'yyyy-MM-dd hh:hh:hh';
//var ServerDate_Time = '2017-02-17 10:45:00';
//console.log(CompareDateTime(ServerDate_Time));
console.log(CompareDateTime(tbl_Event.StartDate + tbl_Event.StartTime))
//function CompareDateTime (ServerDateTime){
function CompareDateTime (tbl_Event.StartDate + tbl_Event.StartTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
}
</script>
assuming your datetime you are getting int tbl_Event.StartDate + tbl_Event.StartTime = 2017-02-17 10:45:00
this will go for your..
var ServerDate_Time = '2017-02-17 10:45:00';
console.log(CompareDateTime(ServerDate_Time));
function CompareDateTime (ServerDateTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
Hope this helps....
Edit after your Edit ....
Updated code...
For Controller --
[HttpGet]
public JsonResult GetEvent(int id)
{
using (IMS2Entities ObjEntities = new IMS2Entities())
{
var ev = from e in ObjEntities.tblEvents
where e.id == id
select e;
return Json(ev.ToList(), JsonRequestBehavior.AllowGet);
}
}
JavaScript code for this
<script>
$(function () {
GetEvent(); // this will call GetEvent function once your DOM is ready, you can call this function on button click or anywhere as per your need.
function GetEvent() {
$.ajax({
type: "GET",
url: "/Home/GetEvent",
data: { Id: '1' }, // '1' is id for my sql database record which is passing to controller to bring back record from server.
success: function (result) {
// result will be collection of list return form server, since you are using id criteria it will always have only 1 record unless you have id as foreign key or something not primary/unique.
// I'm using only first instance of result for demo purpose, you can modify this as per your need.
alert(CompareDateTime(result[0].StartDateTime.substr(6))); // this will alert your true or false, as per I guess this will always return false, as your current date time will never match sql datetime. Still for your requirement.
},
error: function (response) {
alert(response);
}
});
}
function CompareDateTime (ServerDateTimeFormat){
// Convert ServerDateTimeFormat for Comparision
var ServerdateString = ServerDateTimeFormat;
var ServerCurrentTime = new Date(parseInt(ServerdateString));
var Servermonth = ('0' + (ServerCurrentTime.getMonth() + 1)).slice(-2)
var Serverday = ('0' + (ServerCurrentTime.getDate())).slice(-2)
var Serveryear = ServerCurrentTime.getFullYear();
var Serverhours = ('0' + (ServerCurrentTime.getHours())).slice(-2)
var Servermin = ('0' + (ServerCurrentTime.getMinutes())).slice(-2)
var Serversec = ('0' + (ServerCurrentTime.getSeconds())).slice(-2)
var Serverdate = Serveryear + "-" + Servermonth + "-" + Serverday + " " + Serverhours + ":" + Servermin + ":" + Serversec;
// Current Date Time for Comparision
var currentTime = new Date();
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if (date == Serverdate) {
return true;
}else {
return false;
}
}
});
</script>
Please make sure you put reference for JQuery before ... tag.
This is fully working example.. :)

Array not resolving value

let startDate = moment('2016-01-01');
let endDate = moment('2016-01-12');
for (let m = moment(startDate); m.isBefore(endDate); m.add(1, 'days')) {
let queryDate = m.format('DD MMM YYYY');
console.log(queryDate);
queries.push(function (callback) {
processMeterreadings("{ 'params': { 'path': { 'mpan': '2198765119780' },'querystring': {'startdate': '" + queryDate.toString() + " 00:00','enddate': '" + queryDate.toString() + " 23:30','readtype': 'all'}}}",callback);
}
);
}
queries.forEach(function(data){
console.log(data.toString());
})
The values being returned for the last foreach are all the same
function (callback) {
processMeterreadings("{ 'params': { 'path': { 'mpan': '2198765119780' },'querystring': {'startdate': '" + queryDate.toString() + " 00:00','enddate': '" + queryDate.toString() + " 23:30','readtype': 'all'}}}",callback);
}
i would expect the value of the date to be in the item in the array not the variable name.
How do i change it so the item in the array has 2016-01-02 in place of queryDate.toString()?
You are pushing functions into the array, but those functions are never executed. In order to evaluate the string concatenation in the function body, the functions must actually be executed.
Considering building the string outside of the function where the code actually executes, as opposed to pushing the unexecuted code into your array.
You can also build an object literal and use JSON.stringify to handle turning it into JSON for you:
let startDate = moment('2016-01-01');
let endDate = moment('2016-01-12');
for (let m = moment(startDate); m.isBefore(endDate); m.add(1, 'days')) {
let queryDate = m.format('DD MMM YYYY');
console.log(queryDate);
let json = JSON.stringify({
params: {
path: {
mpan: '2198765119780'
},
querystring: {
startdate: queryDate.toString() + ' 00:00',
enddate: queryDate.toString() + ' 23:30',
readtype: 'all'
}
}
})
queries.push(function (callback) {
processMeterreadings(json)
});
}
Alternatively (and preferably), don't build the JSON so early. Just store the date ranges in your array, and iterate over them when you're actually ready to perform the query:
let startDate = moment('2016-01-01');
let endDate = moment('2016-01-12');
for (let m = moment(startDate); m.isBefore(endDate); m.add(1, 'days')) {
let queryDate = m.format('DD MMM YYYY');
queries.push(queryDate);
}
queries.forEach(function(queryDate) {
processMeterreadings(JSON.stringify({
params: {
path: {
mpan: '2198765119780'
},
querystring: {
startdate: queryDate.toString() + ' 00:00',
enddate: queryDate.toString() + ' 23:30',
readtype: 'all'
}
}
}));
});

Unique id attributes needed for second form on page

I have a script that separates the date from a datepicker into day, month, and year. It works fine when there is one form on the page but not when there is a second one (presumably due to the id being the same). How can I add a value to my id and name so that they are unique values?
var now = new Date();
var date = jQuery('.form-date');
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
date.val(today);
jQuery('form').on('submit', function() {
var newVal = date.val().split('-'),
dateParts = {
year: parseInt(newVal[0], 10),
month: parseInt(newVal[1], 10),
day: parseInt(newVal[2], 10)
};
jQuery('.anchor').append(jQuery.map(dateParts, function (index, key) {
var name = 'date_' + key;
return jQuery('<input>', {
type: 'hidden',
name: name,
id: name,
value: dateParts[key]
});
}));
});
Need declare a variable that determines the current form:
(function ($) {
var now = new Date();
var date = $('.form-date');
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
date.val(today);
var form = $('form.reservation');
form.on('submit', function () {
var currentForm = $(this);
var newVal = currentForm.find('.form-date').val().split('-'),
dateParts = {
year: parseInt(newVal[0], 10),
month: parseInt(newVal[1], 10),
day: parseInt(newVal[2], 10)
};
currentForm.find('.anchor').append($.map(dateParts, function (index, key) {
console.log(['date', form.index(currentForm), key].join('_'));
return $('<input>', {
type: 'hidden',
name: ['date', key].join('_'),
id: ['date', form.index(currentForm), key].join('_'),
value: dateParts[key]
});
}));
});
})(jQuery);

Datepicker onchangemonthyear beforeshowday

I have the datepicker on a modal of twitter bootstrap.
in order to highlight some dates, the datepicker is generated in the 'success'-part as an ajax-call.
I manage to highlight the dates I want to highlight in the current month, which is fine.
But when I toggle to the previous or next month, I would like to make that ajax-call again and render dates to highlight. Below you can see my code:
function nonValidated() {
var date = new Date();
date.addDays(-date.getDate() + 1);
var startDate = [date.getDate().lpad(2), (date.getMonth() + 1).lpad(2), date.getFullYear()].join('/');
var enddate = new Date();
enddate.setDate(date.getDaysInMonth());
var endDate = [enddate.getDate().lpad(2), (enddate.getMonth() + 1).lpad(2), enddate.getFullYear()].join('/');
var depId = $('#serviceSelector').val();
$.ajax({
type: "POST",
url: "/ServiceManagement/GetUnassignedSlots",
data: { "from": startDate, "to": endDate, "depId": depId },
success: function (data) {
$.datepicker.setDefaults(
$.extend(
{ 'dateFormat': 'dd/mm/yy' },
$.datepicker.regional['nl-BE']
)
);
$("#nonValidatedDatepicker").datepicker(
{
inline: true,
beforeShowDay: function (date) {
var theday = date.getDate() + '/' +
(date.getMonth() + 1).lpad(2) + '/' +
date.getFullYear();
return [true, $.inArray(theday, data.result) >= 0 ? "warningDate" : ''];
},
onSelect: function (dateText, inst) {
var dateParts = dateText.split('/');
if (dateParts[0][0] == '0') dateParts[0] = dateParts[0][1];
if (dateParts[1][0] == '0') dateParts[1] = dateParts[1][1];
var newdate = new Date(dateParts[2], dateParts[0]-1, dateParts[1]);
var dayOfWeek = newdate.getDay();
if (dayOfWeek == 0) dayOfWeek = 7;
var weekstart = new Date(newdate.getFullYear(), newdate.getMonth(), newdate.getDate());
weekstart.addDays(-dayOfWeek + 1);
var weekend = new Date(newdate.getFullYear(), newdate.getMonth(), newdate.getDate());
weekend.addDays(7 - dayOfWeek);
$('#SelectWeekDate').val([weekstart.getDate().lpad(2), (weekstart.getMonth() + 1).lpad(2), weekstart.getFullYear()].join('/') + ' - ' + [weekend.getDate().lpad(2), (weekend.getMonth() + 1).lpad(2), weekend.getFullYear()].join('/'));
$('#modalNonValidated').modal('hide');
InitFillPage();
},
onChangeMonthYear: function (year, month, widget) {
}
}
);
},
error: function (data) {
},
statusCode: {
401: function (data) {
//ERROR 401: Unauthenticated
window.location.href = '/Account/Login?ReturnUrl=' + encodeURIComponent(window.location.pathname);
}
}
});
}
anyone an idea how I can combine onchangemonthyear and beforeshowday?
I would split the code that shows the datepicker and the code that makes the ajax call to get the data for the datepicker (the data that determines which days to highlight) into 2 separate functions. You can call the function that makes the ajax call from the function that first shows the datepicker, and again from your onChangeMonthYear function. Also, make sure that the ajax call to get the data is made synchronously (set async: false option) so that the data comes back before your beforeShowDay function runs.
Hope that helps!

Categories

Resources