Get the last week date in Javascript - javascript

Here is my issue:
I have 2 RadDatePickers see below:
<telerik:RadDatePicker ID="rdpTimeOfDayFrom" runat="server" Culture="English (United States)">
<DateInput runat="server" DateFormat="MM/dd/yyyy"></DateInput>
</telerik:RadDatePicker>
<telerik:RadDatePicker ID="rdpTimeOfDayTo" runat="server" Culture="English (United States)">
<DateInput runat="server" DateFormat="MM/dd/yyyy"></DateInput>
</telerik:RadDatePicker>
By using JavaScript I want to get the last week date and set it in the rdpTimeOfDayFrom control the issue is the format is:
Mon Mar 09 2015 17:36:58 GMT-0700 (Pacific Daylight Time)
How can I can I set the return date in that format("yyyy/MM/dd") using Javascript? the reason I'm asking is because after I'm doing post back and trying to get what inisde the control it's been display like that:
3/9/2015 12:00:00AM and I need only the date.
Here is my JS Function:
Using MomentJS
function SetLastWeekDate(sender, args) {
var lastWeekDate = $find("<%=btnTimeOfDayLastWeek.ClientID %>");
var fromDate = $find("<%=rdpTimeOfDayFrom.ClientID %>");
var toDate = $find("<%=rdpTimeOfDayTo.ClientID %>");
var today = new Date();
if (lastWeekDate.get_checked()) {
fromDate.clear();
toDate.clear();
//var lastWeekPeriod = new Date(today.getFullYear(), today.getMonth(),today.getDate() - 7);
var lastWeekPeriod = moment().subtract(7, 'd').format('l');
fromDate.set_selectedDate(lastWeekPeriod);
toDate.set_selectedDate(today);
}
}

this is easy to do with MomentJs
function SetLastWeekDate(sender, args) {
var lastWeekDate = $find("<%=btnTimeOfDayLastWeek.ClientID %>");
var fromDate = $find("<%=rdpTimeOfDayFrom.ClientID %>");
var toDate = $find("<%=rdpTimeOfDayTo.ClientID %>");
var today = moment();
if (lastWeekDate.get_checked()) {
fromDate.clear();
toDate.clear();
var lastWeekPeriod = moment().subtract(7, 'd').format("YYYY/MM/dd");
fromDate.set_selectedDate(lastWeekPeriod);
toDate.set_selectedDate(today);
}
}
if you can set the local of moment to a locale that uses YYYY/MM/DD as the default date display you can simply call format('L'). L is a shortcut in Moment to the locale's default date display.

If I understand well, you need to substract 7 days to the current date.
How about :
Solution 1, with vanilla Javascript :
var d = new Date(); // <- Get the current date
d.setDate(d.getDate() - 7); // <- Substract 7 days
Then format it (this part is a bit weird without library) :
var year = d.getFullYear(),
month = ('00' + (d.getMonth() + 1)).slice(-2),
day = ('00' + d.getDate()).slice(-2);
var formattedDate = year + '/' + month + '/' + day;
Explanation :
d.getMonth() is zero-based so we have to add one
('00' + *number*).slice(-2) is for formatting the number on two digits.
Solution 2 :
If you often need to do some computation or formatting with dates, consider working with a library like momentjs or Date.js. That will really simplify the task. For example, substracting seven days and formatting the date to YYYY/MM/DD with momentjs looks like that :
moment().subtract(7, 'days').format('YYYY/MM/DD');

Related

How to format JSON dates with JavaScript?

I have an HTML <input type="date" name="departing" /> which returns for example the date in the following format: 2021-11-07
When I forward this variable to my handlebars, it is being displayed as follows:
Mon Nov 08 2021 01:00:00 GMT+0100 (Central European Standard Time)
I would like to have it displayed as:
07/11/2021
I tried formatting it with date-fns like this:
departing = format(parseISO(departing.getDate()), "dd/MM/yyyy");
But then my handlebar shows: "Invalid Date"
I am so confused. Any ideas on how to get that date to be displayed in the 07/11/2021
format?
First of all create a date object
const newDate = new Date();
Now you can manipulate code to get answer whatever you want
var outputDate = newDate .getDate() + "/" + (newDate.getMonth()+1) + "/" +
newDate.getFullYear();
Output will be looks like 01/11/2021
Well you could go as simple as using #getDate(), #getMonth() and #getFullYear() methods separately then displaying them in the order you'd like like so:
const date = new Date(departing);
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
console.log(`${day}/${month}/${year}`);
Hope it answers the question.
You could do it by several ways
method 1:-
let n = new Date()
console.log(n.toLocaleDateString("en-US")
output=== 31/9/2021
method 2 :- get separate values and merge
let n = new Date()
console.log(n.getDate()+"/"+n.getMonth()+"/"+n.getFullYear())
output=== 31/9/2021

Default date format of Javascript/Jquery

I have a kendo date picker which is set to format date as "MM/dd/yyyy". I want to check using jquery/javascript that if kendo date picker date must not be future date and date must be greater than '01/01/1900'.
The issue I am facing is when I take new date in script, it is like Date {Tue Jun 10 2014 11:17:48 GMT+0530 (India Standard Time)}. and my kendo date picker has value in 06/02/2012 format. I don't know how to compare it.
I know a method in kendo date picker named: parseFormats in which I have to give parsing format, but I don't know defualt date format of Javascript/Jquery and I don't know how to do it.
Kendo Date Picker
#(Html.Kendo().DatePickerFor(m => m.DateOfBirth).Format("MM/dd/yyyy").HtmlAttributes(new { style = "width:100%", Placeholder = "mm/dd/yyyy" }).Max(DateTime.Now.Date).Min(new DateTime(1900, 1, 2).Date))
You are getting the toString value of the new Date. Try this
var d = new Date(datepicker.value()); // looked at the docs, no obvious shortcut
if (d.getFullYear()<1900) alert("nope");
or
var now = new Date(), d = new Date(datepicker.value());
now.setHours(0,0,0,0); // normalise
if (d.getTime() > now.getTime()) alert("Please no future dates");
More information about JS Dates: MDN
You can also make it harder to select the invalid dates
$("#datetimepicker").kendoDateTimePicker({
value:new Date(),
min: new Date(1900,0,1), // JS months are 0 based!
max: new Date()
});
And lastly add the validation
$("#MyForm").kendoValidator({
rules: {
//implement your custom date validation
dateValidation: function (dateField) {
var currentDate = Date.parse($(dateField).val());
//Check if Date parse is successful
if (!currentDate) {
return false;
}
var now = new Date(), then=new Date(1900,0,1),d = new Date($(dateField).val());
now.setHours(0,0,0,0); // normalise
return d.getTime() >= then.getTime() && d.getTime() < now.getTime()
}
},
messages: {
//Define your custom validation massages
required: "Date is required message",
dateValidation: "Invalid date message"
}
});
Default Date Format of Javascript is MM/DD/YYYY
For Reference Follow Date Format
I would pretty much ignore Kendo's methods altogether and use moment.js in a validation function when you submit. You can format each date, min, max, and candidate, as YYYY-MM-DD, then compare using built-in .isAfter() and .diff() queries. Remember that you have to account for if they type something, not just pick it from the calendar, so you have to ensure you have 2-digit days. You also have to account for if someone enters in something outrageous that is higher than the Kendo control can deal with, like 1/1/0001 and 1/1/9000. Code below deals with that. You may also - though I did not include it here in my code, but did in my fiddle - want to account for if the year is only 2-digits, as well:
$('#btnValidate').click(function(){
var minDate = moment('1900-1-1');
var maxDate = moment(Date.parse(new Date()));
//var dateField = $("#datepicker").data("kendoDatePicker").value();
var dateField = $("#datepicker").val();
// Moment requires YYYY-MM-DD
dateField = dateField.replace('/','-').replace('/','-');
var year = dateField.split('-')[2];
var month = dateField.split('-')[0];
var day = dateField.split('-')[1];
if (month < 10 && month.toString().length == 1) { month = "0" + month; }
if (day < 10 && day.toString().length == 1) { day = "0" + day; }
dateField = year + '-' + month + '-' + day;
// Enter into moment and compare
var dateToConsider = moment(dateField);
var lowerLimitBreached = dateToConsider.diff(minDate) < 0;
var upperBoundBreached = dateToConsider.isAfter(maxDate);
alert('min: ' + moment(minDate).format('MM/DD/YYYY'));
alert('max: ' + moment(maxDate).format('MM/DD/YYYY'));
alert('our candidate: ' + moment(dateToConsider).format('MM/DD/YYYY'));
if(lowerLimitBreached || upperBoundBreached)
alert('Invalid date');
else
alert('Valid date');
});
http://jsfiddle.net/navyjax2/k5xx9xpu/
Note that the example doesn't show using times, but you could add that if you got the time from the .data("kendoDatePicker").value commented-out line. I just would not trust the year since "0001" will translate as "1901". So I would say that appending the time to the dateField object would be the way to go, and you can hard-code the time on it like moment(year + '-' + month + '-' + day + 'T' + hours + ':' + mins + ':' + secs + 'Z').utc() and the min like moment('1900-1-1T00:00:00Z'), though 00:00:00Z is already implied if you do not set it.
You can use KendoUI's datepicker method as shown below:
var datepicker = $("#datepicker").data("kendoDatePicker");
var value = datepicker.value();
Here value will be holding value like Tue Oct 11 2015 11:17:48 GMT+0530 (India Standard Time)
Now you can use simple condition to compare values
EDIT
You can refer demo at this fiddle
Once you have javascript date format you can use condition to compare dates, as I have in demo code

See if date selected is future from today - JavaScript

I have to compare the date that they want to put in and the current date today, and if they have put in a date that is in the future, then alert them to change the date, otherwise insert the data.
Basically I am having issues comparing the dates. here is my code:
var today = year + '-' + month + '-' + day + ' 00:00:00';
var d1 = new Date(postdate); // postdate = 2014/02/01 ie: 1 Feb 2014
var d2 = new Date(today); // todays date
if(d1>d2){
alert('You cannot post in the future!');
}
But that doesnt seem to work. Where am I going wrong?
Convert the dates into a comparable number, like milliseconds.
if(d1.valueOf()>d2.valueOf()){
alert('You cannot post in the future!');
}
You don't need to create a new variable today.
If by today you are trying to get today's date, you can simply do
var today = new Date();
var d1 = new Date(postdate); // postdate = 2014/02/01 ie: 1 Feb 2014
//----------
var d2 = new Date(year,month,day); // todays date
//----------
if(d1>d2){
alert('You cannot post in the future!');
}
Remember month is 0 based index. So, for december it would be 11.
Compare the dates with the same format, if today is 2014-01-24 00:00:00 then postdate also should be 2014-02-01 00:00:00
Then use + prefix to compare milliseconds:
if(+d1 > +d2){
alert('You cannot post in the future!');
}

How can I add a day to user's input? [duplicate]

This question already has answers here:
How to add days to Date?
(56 answers)
Closed 9 years ago.
I have a textfield that inputs date in this format: yyyy-mm-dd, how can I add a day to that users input? I have the following code but it doesnt work...
users_date = document.getElementById('users_date').value;
var date = new Date(users_date);
var next_date = new Date();
next_date .setDate(date.getDate()+1);
document.getElementById('next_date').value = next_date;
The first problem is the format of the date in the second is like 'Mon Aug 05 2013 16:24:40 GMT-0500 (Hora est. Pacífico, Sudamérica)'
The second problem is that when the user input the fist day of the month like '2013-01-01' or '2013-08-01' it displays 'Sun Sep 01 2013 16:26:06 GMT-0500 (Hora est. Pacífico, Sudamérica)' ALWAYS
For example if user inputs 2013-01-01 I want another textfield to be 2013-01-02 or 2013-08-31 it displays 2013-09-01, how can I do that?
Thanks!!
ITS NOT DUPLICATE BECAUSE THE OTHER POST DOESN'T FORMAT THE DATE!!!!
Prior to ES5 there was no standard for parsing dates. Now there is a format that is a version of ISO8601, however it isn't supported by all browsers in use and is not typically used for user input.
Normally a format is requested or a "date picker" used that returns a specific format. From there, it's quite simple to parse the string to create a Date object:
// s is date string in d/m/y format
function stringToDate(s) {
var b = s.split(/\D/);
return new Date(b[2], --b[1], b[0]);
}
For ISO8601 format (y-m-d), just change the order of the parts:
// s is date string in y/m/d format
function isoStringToDate(s) {
var b = s.split(/\D/);
return new Date(b[0], --b[1], b[2]);
}
To add one day to a Date object, just add one day:
var now = new Date();
var tomorrow = now.setDate(now.getDate() + 1);
This should work:
var date = new Date(document.getElementById('users_date').value);
var next_date = new Date(date.getTime() + 24*60*60*1000); // adding a day
document.getElementById('next_date').value = next_date.getFullYear() + "-" +
(next_date.getMonth()++) + "-" + next_date.getDate();
Please, note that Date#getMonth() is zero-based. Hence, the increment.

How to format a date pulled from a form field with javascript

I have a date picker that generates a date like 6/30/2012 in a form field.
I need to convert this date to 2012-06-30 for mysql. I can get it close with the following.
var datePart=document.getElementById('formdate').value.split(/[^0-9]+/);
and then use to generate the date.
datePart2[2] + "-" + datePart2[1] + "-" + datePart2[0]
The problem is it gived me the date 2012-6-30 instead of 2012-06-30.
Is there an easier way to do this? Or a way to use my current method and ad a zero to the front of a digit if it is a single digit?
The Open Source date.js ( http://www.datejs.com/ )provides a really extensive framework for JavaScript dates, IMHO superior to the jQuery plug-in. It may be more than you need for this requirement, but I think it is a welcome addition to any JavaScript programmers's arsenal.
To format your example:
var mySqlDate = Date.parse('6/30/2012').toString('yyyy-MM-dd');
Are you using jQuery? if so you could use the Date Format plugin, makes date manipulation easy
http://archive.plugins.jquery.com/project/jquery-dateFormat
try this, hope this help:
Format date in jquery- from Sat Mar 03 2012 14:16:05 GMT+0530 to 03/03/2012
important you need to put a check condition like this one and if its less then 10 append 0 [code] date < 10 ? "0"+date : date; cheers!
something on the line of this:
function dateFormatFoo(){
var d = new Date();
date = d.getDate();
date = date < 10 ? "0"+date : date;
mon = d.getMonth()+1;
mon = mon < 10 ? "0"+mon : mon;
year = d.getFullYear()
return (date+"/"+mon+"/"+year);
}
Based on your example, a simple function is:
var formatUStoISOdate = (function() {
function aZ(n) {
return (n<10? '0' : '') + n;
}
var re = /[^0-9]/;
return function(d) {
var d = d.split(re);
return d[2] + '-' + aZ(d[0]) + '-' + aZ(d[1]);
// or
// return [d[2], aZ(d[0]), aZ(d[1])].join('-');
}
}());
alert(formatUStoISOdate('3/31/2011')); // 2011-03-31

Categories