How do I get the Monday of the current week? - javascript

(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
var day = new Date(date);
var getMonday = day.getDay(),
diff = date.getDate() - getMonday + (getMonday == 0 ? -6:1);
field.value = new Date(date.setDate(diff));
console.log(date);
})();
I am trying to get the Monday of the current date.
I keep getting errors about it and not sure how to resolve it
TypeError: date.getDate is not a function
at index.html:394
at index.html:398
(anonymous) # index.html:394
(anonymous) # index.html:398
Post of so called Duplicate only asks for the how to get the date. My question has similar code but I am getting error messages that was never addressed in the question

You transform the date to string in the first line:
date = new Date().toISOString().substring(0, 10) that is what causes the error... date is no longer a Date object.
--- EDIT: Solution
I would suggest you to either declare an additional variable for any of your later use as ISO string, or to make the conversion after only when output:
For this, I'd suggest add your format to the Date object's prototype
Date.prototype.myFormat = function() {
return this.toISOString().substring(0, 10);
}
Update your initial code like this:
var date = new Date(),
str_date=date.toISOString().substring(0, 10),
field = document.querySelector('#date'),
day = new Date(date),
getMonday = day.getDay(),
diff = date.getDate() - getMonday + (getMonday == 0 ? -6:1);
console.log(date);
console.log(str_date);
console.log(new Date(date.setDate(diff)));
console.log(new Date(date.setDate(diff)).myFormat());
//Now you can update your field as needed with date or string value
field.value = new Date(date.setDate(diff));
field.value = new Date(date.setDate(diff)).myFormat();
If you need it in more places make the getMonday also a function...
Happy coding,
Codrut

Related

Angular 6: Invalid time value

I am trying to get two date and times as a string of numbers (epoch) so I can compare them. One is a new Date():
today = new Date().valueOf();
And one is from an api response in the format:
scheduleDate: "2019-07-22T00:00+01:00"
The issue is I am trying to get the returned date in the correct format. When I try
var scheduleDate = new Date(scheduleDate).toISOString()
console.log("converted date:" + scheduleDate);
I get the error:
Invalid time value
How do I get the returned date into epoch format?
Thanks
Your scheduleDate variable must be undefined. Are you sure it's being assigned properly?
(function() {
//number (milleseconds)
const today = new Date().valueOf();
//string
const scheduleDate = undefined; //"2019-07-22T00:00+01:00";
const scheduleDate2 = new Date(scheduleDate).toISOString()
console.log(typeof today);
console.log(typeof scheduleDate);
console.log("converted date: " + scheduleDate);
}
)();
More worryingly, why are you converting a date string to a date and then back to a string (same value).
You are missed to assign the value
scheduleDate= "2019-07-22T00:00+01:00"
Then try its working
> scheduleDate= "2019-07-22T00:00+01:00"
'2019-07-22T00:00+01:00'
> new Date(scheduleDate)
2019-07-21T23:00:00.000Z
> var scheduleDate = new Date(scheduleDate).toISOString()
undefined
> scheduleDate
'2019-07-21T23:00:00.000Z'
> console.log("converted date:" + scheduleDate);
converted date:2019-07-21T23:00:00.000Z

(getDate() - 1) function is getting the value zero if the current date is 1

My Requirement:
I'm having to fields Start Date and End Date, If the End Date is left empty while saving the record, the End Date Field value is populated with plus 1 year based on the entered from date.
My Issue:
If the Start Date is "9/1/2016" and the End Date is Left Empty means it should automatically populate the End Date value as "8/31/2016" but it returning the End Date value as "9/0/2016" and also i'm getting the following ERROR MESSAGE
Error: JS_EXCEPTION
INVALID_FLD_VALUE You have entered an Invalid Field Value Invalid Date for the following field: custrecord_end_date
CODE:
SCRIPT : CLIENT SCRIPT, EVENT :SaveRecord
function saveRecord(scriptContext) {
var newRecord= scriptContext.currentRecord;
var fromDate = new Date(newRecord.getValue('custrecord_created_date'));
var endDate = newRecord.getValue('custrecord_end_date');
if (endDate == null || endDate == '') {
//getting plus 1 year based on the From Date
tempEndDate = addingPlusYearOfTheCurrentDate(fromDate);
//setting the value to the End Date Field
newRecord.setValue('custrecord_end_date', tempEndDate);
}
}
// Add Plus Year from the Start Date when the End Date is Empty
function addingPlusYearOfTheCurrentDate(fromDate ) {
var date = new Date();
var Month = (fromDate.getMonth() + 1);
var Dates = (fromDate.getDate() - 1);
var Year = (fromDate.getFullYear() + 1);
var last_Day = new Date(Month + '/' + Dates + '/' + Year);
log.debug('last_Day:', last_Day);
return last_Day;
}
Not sure why you expected to be able to subtract 1 from 1 and get anything other than 0, but you can solve this problem by using the Date object's setFullYear() and setDate().
function addingPlusYearOfTheCurrentDate(fromDate) {
var date = new Date(fromDate);
date.setFullYear(date.getFullYear() + 1);
date.setDate(date.getDate() - 1);
return date;
}
console.log(addingPlusYearOfTheCurrentDate(new Date(2015, 10, 1)));
You should use the method nlapiStringToDate() for string to date conversions, as NetSuite gives date field value as string, which you must convert to date, and before you set back date, you must use nlapiSetFieldValue(YOUR_FIELD_ID, nlapiStringToDate(dateObject))
Please see below on suggested usage on reading and setting date fields.
function saveRecord(scriptContext) {
var newRecord = scriptContext.currentRecord;
var fromDate = nlapiStringToDate(newRecord.getValue('custrecord_created_date'));
var endDate = nlapiStringToDate(newRecord.getValue('custrecord_end_date'));
if (endDate == null || endDate == '') {
//getting plus 1 year based on the From Date
tempEndDate = addingPlusYearOfTheCurrentDate(fromDate);
//setting the value to the End Date Field
newRecord.setValue('custrecord_end_date', nlapDateToString(tempEndDate));
}
Parsing strings with the Date constructor (and Date.parse, they are equivalent for parsing) is strongly recommended against since parsing is almost entirely implementation dependent and inconsistent. Manually parse strings with a custom function or use a library.
Adding a year to a Date is fairly simple, but it seems you want the date that is one day prior to the same date next year. So add one year then subtract one day.
// Parse m/d/y format string to a Date and validate the result
function parseMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[0], b[1]);
return d && d.getMonth() == b[0]? d : new Date(NaN);
}
// Add 1 year to a Date
function addYear(d) {
if (Object.prototype.toString.call(d) != '[object Date]') return;
d.setFullYear(d.getFullYear() + 1);
d.setDate(d.getDate() -1);
return d;
}
var d = parseMDY('9/1/2016');
console.log(d.toLocaleString())
addYear(d);
console.log(d.toLocaleString())
Note that for 29 February, adding one year gives 1 May, then subtracting one day will give 28 February.
Is this a 1.0 or 2.0 script?
NetSuite's 1.0 API offers a couple date manipulation methods that might be helpful to you here: nlapiAddMonths and nlapiAddDays, as well as the Date-String conversion methods.
Here's an example of what you could do in 1.0
// 1.0 API does not pass scriptContext to saveRecord
function saveRecord() {
// Use nlapiStringToDate instead of raw Date constructor
var fromDate = nlapiStringToDate(nlapiGetFieldValue('custrecord_created_date'));
// Instead of the full extra conditional, just use || as fallback
var endDate = nlapiStringToDate(nlapiGetFieldValue('custrecord_end_date')) ||
calculateEndDate(fromDate);
// setting the value to the End Date Field
nlapiSetFieldValue('custrecord_end_date', nlapiDateToString(endDate));
}
/** #param fromDate {Date} */
function addYear(fromDate) {
return nlapiAddMonths(fromDate, 12);
}
/** #param fromDate {Date} */
function dayBefore(fromDate) {
return nlapiAddDays(fromDate, -1);
}
/** #param startDate {Date} */
function calculateEndDate(startDate) {
// add 1 year first, then subtract one day
return dayBefore(addYear(startDate));
}
If you're using 2.0 just add a comment, and I will try to update the example if I can. If you've got any questions about how this works, feel free to let me know as well.

ReferenceError: date is not defined

I have some code here where I get a value from a form represented by "adate". Then I split the string the user enters at the hyphen and separate each value into year, month and day as you can see. I use those values to define a date object. My console correctly displays the date, but I keep getting this error also showing up. Am I defining the date incorrectly? I'm not sure what the issue is.
function getFormData() {
var task = document.getElementById("task").value;
if (checkInputText(task, "Please enter a task")) return;
var who = document.getElementById("who").value;
if (checkInputText(who, "Please enter a person to do the task")) return;
var adate = document.getElementById("dueDate").value;
var reString = new RegExp("[0-9]{4}\\-\[0-9]{2}\\-\[0-9]{2}");
if ( adate.match(reString)) {
processDate(adate) }
else {
alert("you did not enter the date in the correct format")
};
var id = (new Date()).getTime();
var todoItem = new Todo(id, task, who, date);
todos.push(todoItem);
addTodoToPage(todoItem);
saveTodoItem(todoItem);
hideSearchResults();
}
function processDate(adate) {
var splitArray = new Array();
splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
var date = new Date(year, month, day);
console.log(date);
}
Make your function return the date, because the date variable in there is not visible to the outside:
function processDate(adate) {
var splitArray = new Array();
splitArray = adate.split("-");
var year = splitArray[0];
var month = splitArray[1] - 1;
var day = splitArray[2];
return new Date(year, month, day);
}
Then assign to a new variable when you call it:
var date = processDate(adate);
The error actually originated in the following line, because you were referencing a non-existing date variable:
var todoItem = new Todo(id, task, who, date);
Just a comment.
The RegExp constructor is usually only required where the expression is dynamically generated. Where you have a fixed expression, it's simpler to use a literal (as you don't have to quote certain characters). Also, to test the format, a more appropriate method is test rather than match.
If the date format is: yyyy-mm-dd, consider:
var reString = /^\d{4}-\d\d-\d\d$/; // trim leading and trailing white space?
if (reString.test(adate)) {
processDate(adate);
}
The date string validation should be in the processDate function, which might throw different errors depending on whether the format is incorrect or the date is invalid (e.g. 2013-02-29, which will return a date of 2013-03-01 in your current code).

Need explanation of this Date Processing function

Could anyone please explain the below code to me?
For example, i would like to set Today's date to today (21st of November, 2012) and the end date to the 3rd of December.
The reason for this is because i want to loop through a list of items, determine whether they are in the "past", "present" or "future" and assign a class to them accordingly.
I hope this makes sense! Any help is greatly appreciated and much welcomed!
function daysTilDate(expiredate){
expiredate ="12/"+expiredate+"/2012";
var thisDay=new Date(expiredate);
var CurrentDate = new Date();
var thisYear=CurrentDate.getFullYear();
thisDay.getFullYear(thisYear);
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
DayCount=Math.round(DayCount);
return DayCount;
}
You can simplify the method like below if you want to calculate the days to an expire date. Please note that if you don't specify a test date, it'll take the current date as the test date.
​function ​daysTilData(expireDate, testDate) {
if(typeof testDate === "undefined"){
testDate = new Date(); // now
}
var diff = expireDate - testDate;
// minus value meaning expired days
return Math.round(diff/(1000*60*60*24));
}
alert(daysTilData(new Date("12/31/2012")));
// result 40
alert(daysTilData(new Date("12/31/2012"), new Date("1/12/2013")));
// result -12
Here's a line by line explanation.
The function declaration...
function daysTilDate(expiredate){
Takes the parameter expiredate sets it equal to the same value with "12/" prepended and "/2012" appended. so if the value of expiredate was "10", the new value is now "12/10/2012"...
expiredate ="12/"+expiredate+"/2012";
Instantiates a new Date object named thisDay using the expiredate string...
var thisDay=new Date(expiredate);
Instantiates a new Date object named CurrentDate, using the default constructor which will set the value equal to today's date...
var CurrentDate = new Date();
Gets just the Year segment from CurrentDate (which was earlier set to today's date)...
var thisYear=CurrentDate.getFullYear();
Gets the Year segment from thisDay (which was earlier set to "2012")...
thisDay.getFullYear(thisYear);
Gets the difference between thisDay and CurrentDate, which is in milliseconds, and multiplies that by 1000*60*60*24 to get the difference in days...
var DayCount=(thisDay-CurrentDate)/(1000*60*60*24);
Rounds the previously calculated difference...
DayCount=Math.round(DayCount);
Returns the difference between today and the passed-in day in December 2012...
return DayCount;
}
Note that the 2 lines that get the year segments are extraneous, because those values are never used...
I am not going to review the code, but I can answer your question of "I want to loop through a list of items, determine whether they are in the past, present, or future".
First, you want to construct your target date. If it's "now", just use new Date(). If it's a specific date, use new Date(dateString).
Second, Date objects in JavaScript have various members that return the date's characteristics. You can use this to compare dates. So, let's say you have your date strings in an array:
function loopDates(targetDateString, myDates) {
var targetDate, nextDate, status, ix;
targetDate = new Date(targetDateString);
for (ix = 0; ix < myDates.length; ++ix) {
nextDate = new Date(myDates[ix]);
if (nextDate.getFullYear() < targetDate.getFullYear()) {
status = "past";
} else if (nextDate.getFullYear() > targetDate.getFullYear()) {
status = "future";
} else {
// Year matches, compare month
if (nextDate.getMonth() < targetDate.getMonth()) {
status = "past";
} else if (nextDate.getMonth() > targetDate.getMonth()) {
status = "future";
} else {
// Month matches, compare day of month
if (nextDate.getDate() < targetDate.getDate()) {
status = "past";
} else if (nextDate.getDate() > targetDate.getDate()) {
status = "future";
} else {
// Day matches, present
status = "present";
}
}
}
console.log("Date " + myDates[ix] + " is " + status + " from " + targetDateString);
}
}
loopDates("11/17/2012", ["11/16/2012", "11/17/2012", "11/18/2012"]);
This will log:
Date 11/16/2012 is past from 11/17/2012
Date 11/17/2012 is present from 11/17/2012
Date 11/18/2012 is future from 11/17/2012
Working jsFiddle here.
If you want to work with a comprehensive Date class, use DateJS, an open source JavaScript date and time processing library with some impressive features.

jQuery string Comparison?

I'm comparing two dates and my code goes like this.
jQuery('.newAppointment a.ui-state-default').click(function() {
var date = jQuery(this).parent().attr('title');
var d = jQuery.datepicker.parseDate('dd/mm/yy',date.toString());
alert(d);
var today = new Date;
var t = jQuery.datepicker.parseDate('dd/mm/yy',today.toString() );
alert(t)
if(t > d){
url = "/users/" + user_id + "/events/new?type=Surgery"+"&day=" + escape(date);;
window.location = url;
}else{
alert("you cannot add appointment to past dates");
}
});
but am getting error in firebug.
uncaught exception: Missing number at position 0
can anyone tell me where I'm doing wrong.
From the fine manual:
parseDate(format, value, settings)
[...]
A number of exceptions may be thrown:
'Missing number at position nn' if format indicated a numeric value that is not then found
So your error is coming from jQuery-UI. The format you get from date.toString() depends on the browser and the locale, there's no reason to expect it always be dd/mm/yy and in your case, it isn't.
Your date is already a string and in a known format (presumably dd/mm/yy) so you should be able to do this:
var d = jQuery.datepicker.parseDate('dd/mm/yy', date);
to get a Date. Then you can get today with just:
var today = new Date;
and compare them directly:
if(today > d)
If you want to throw away the hours, minutes, and seconds then:
var now = new Date;
// Or set milliseconds, seconds, minutes, and hours to zero.
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
if(today > d)
may be there is some problem with parseDate()
You can compare the dates just by using just
if (today > date){...}

Categories

Resources