Difference of two locale date in jquery - date

I am getting the date from CJuidatepicker with language such de,en,nl.
Now i need to find the difference between two dates in jquery accordnig to the language selected.
My Code is
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate()-1;
var output = d.getFullYear() + '-' +
((''+month).length<2 ? '0' : '') + month + '-' +
((''+day).length<2 ? '0' : '') + day;
var dateString1 = $('#Jobs_valid_date').val();
var dateString2= output;
var dateDiff = function ( dateString2, dateString1 ) {
var diff = Math.abs(dateString2 - dateString1);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000);
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000);
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000);
} else {
return "< 1 minute";
}
};
var new_date = dateDiff(new Date(dateString2), new Date(dateString1));
var sum = (parseInt(new_date * feature) + parseInt(fixed))
It retuns NAN.. Please help me to solve this

Doing it from scratch is not recommended for several reasons. If using a library is not a constraint, use moment.js. It has methods to calculate date differences. It has internationalization support too. In case your locale is not supported you can add it yourself. If you add a new locale, you are welcome to contribute it to the moment.js community.

Try this out, this worked for me. I wanted to calculate difference between the 2 dates which the client inputs.
function calculate(start_date,end_date)
{
var t1= start_date ;
var t2= end_date;
// The number of milliseconds in one day
var one_day=1000*60*60*24;
//Here we need to split the inputed dates to convert them into standard format
var x=t1.split(“/”);
var y=t2.split(“/”);
//date format(Fullyear,month,date)
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0]);
//Calculate difference between the two dates, and convert to days
numberofDays=Math.ceil((date2.getTime()-date1.getTime())/(one_day));
// numberofDays gives the diffrence between the two dates.
$(‘#Input_type_text).val(numberofDays);
}

Related

DateTime fromMillisecondsSinceEpoch returning Incorrect Values

So, I'm working on a converter for changing JDE Julian Dates to Gregorian Dates and Vice Versa. I've run into a weird problem that I cannot find an answer for in my Julian to Gregorian code where non-leap years are calculating as leap years and leap years are calculating as non-leap years.
Exp: When I enter the JDE Julian Date '122095' it should return 04/05/2022 but instead returns 04/06/2022. When I changed the year to 2020, a leap year, it returned todays correct date of 04/05/2022 when it should have returned 04/04/2020.
I think the problem might be with my DateTime.fromMillisecondsSinceEpoch converter because it is return 2022-04-06 06:00:00.000Z and I don't know where the 6 in the hour spot is coming from or how to cancel it out. My Code is below.
Edit: I forgot, I used the code originally from THIS post.
Edit Edit: Okay that fixed the problem, I set "var millisecondsSinceEpoch = DateTime(convYear()).millisecondsSinceEpoch;" to "var millisecondsSinceEpoch = DateTime.utc(convYear()).millisecondsSinceEpoch;" and it was still giving me the wrong answer. I then thought to take the "isUtc: True" off of the end of "var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch((millisecondsSinceEpoch + millisDayOfYear));" and that fixed the issue. The best I can figure is having the UTC bool at the end of that line was preventing millisecondsSinceEpoch from actually converting to UTC.
Thanks jamesdlin and James Heap for your help!
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
gregDate(var inputDate) {
var inputDate = '122095';
// Break down JDE date into individual pieces
var currentYear = int.parse(DateFormat('yy').format(DateTime.now()));
print('Current Year: $currentYear');
var splitYear = int.parse(inputDate.substring(1, 3));
print('Split Year: $splitYear');
var splitDay = int.parse(inputDate.substring(3, inputDate.length));
print('Split Day: $splitDay');
// Uses the current year to determine if our 2 digit date needs a 19 or 20 in the front
convYear() {
if (splitYear <= currentYear) {
var year = '20' + splitYear.toString();
return int.parse(year);
}
else {
var year = '19' + splitYear.toString();
return int.parse(year);
}
}
print('Converted Year: ${convYear()}');
// Takes 3 digit day in year and converts it to formatted date time.
convDate() {
var dayOfYear = splitDay;
var millisInADay = Duration(days: 1).inMilliseconds; // 86400000
print(millisInADay);
var millisDayOfYear = dayOfYear * millisInADay;
print(millisDayOfYear);
var millisecondsSinceEpoch = DateTime.utc(convYear()).millisecondsSinceEpoch;
print(millisecondsSinceEpoch);
var dayOfYearDate = DateTime.fromMillisecondsSinceEpoch((millisecondsSinceEpoch + millisDayOfYear), isUtc: true);
var result = DateFormat('MM/dd/${convYear()}').format(dayOfYearDate);
print(dayOfYearDate);
print(result);
return result;
}
return convDate();
}

Changing Pentaho date values to first and last day of the week in Javascript Modified Value

I am trying to set two variables to the first and last day of the week for a given date, but the .setDate() method does not seem to be changing the date and 'lastday' and 'firstday' variables return an Invalid Date (1970)
DateNew is from my input step which is defined as dd/MM/yyyy format
var curr = DateNew;
var first = getDayNumber(curr,"d") - getDayNumber(curr,"wm")
var last = first + 7;
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
Declaring the input variable as a date seemed to resolve the issue as there was no javascript type associated with it.
var curr = new Date(DateNew);
var first = getDayNumber(curr,"d") - getDayNumber(curr,"wm")
var last = first + 7;
var firstday = new Date(curr.setDate(first)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();

Compare data with present date google script

Hi i want to compare column with date (i.e "Referral Date" column)
with present day , here is what i have
function newF(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
var range = ss.getDataRange();
var headers = range.getValues()[0];
var colIndex = headers.indexOf("Referral Date");
var today = new Date();
var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
for (i=0;i<range.getLastRow();i++){
var dates = searchRange.getValues();
if (today.valueOf()>dates.valueOf()){
updatelFilter()
} else{
SpreadsheetApp.getUi().alert('Future Date Error');
break;
}
}
}
The problem i have is, it throws alert Future Date Error irrespective of date in column (Referral Date). Let me know if additional information is required.
My goal:
1)if date column (Referral Date) is greater than present date : Throw alert error & should not run updateFilter
2)if (Referral Date) is lesser than present date: Run updateFilter function
Issues
searchRange.getValues() yields a two dimensional array. So dates[0][0] points to a date, while dates[0] points to an array.
var dates = searchRange.getValues(); is being called inside the loop repeatedly, when it should ideally be called outside once since the value will not change; calling it inside the loop is costly and redundant
for (i=0;i<range.getLastRow();i++){ the condition can be replaced with i<dates.length if point 2 is followed
if (today.valueOf()>dates.valueOf()){ I believe is supposed to have dates[0] instead
Modified Code
function newF(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Worksheet');
var range = ss.getDataRange();
var headers = range.getValues()[0];
var colIndex = headers.indexOf("Referral Date");
var today = new Date();
var searchRange = ss.getRange(2,colIndex+1,ss.getLastRow()-1);
var dates = searchRange.getValues().map(d=>d[0]);
for (i=0;i<dates.length;i++) {
if (today.valueOf()>dates[i].valueOf()){
updateFilter()
} else {
SpreadsheetApp.getUi().alert('Future Date Error');
break;
}
}
}
To run updateFilter only if no future dates
Replace the loop with the following -
if(dates.some(d => today.valueOf() < d.valueOf())) {
SpreadsheetApp.getUi().alert('Future Date Error');
} else {
for (let i=0; i<dates.length; i++) {
updateFilter();
}
}

map invoke failed: JS Error: Error: fast_emit takes 2 args (anon):1

A collection will be created from the below js file , i need three Fields in my collection so i have given
emit(this.cust_id, 1,date);
Its giving the below Error
map invoke failed: JS Error: Error: fast_emit takes 2 args (anon):1
But its working fine with emit(this.cust_id, 1);
Please tell me ow to include date aslo in the collection created ??
m = function() {
var currentDate = new Date();
currentDate.setDate(currentDate.getDate()-1);
var month = (currentDate.getMonth() < 9 ? "0"+ (currentDate.getMonth()+1) : (currentDate.getMonth()+1));
var day = (currentDate.getDate() < 10 ? "0" + currentDate.getDate() : currentDate.getDate());
var date = currentDate.getTime();
emit(this.cust_id, 1,date);
}
r = function (k, vals) { var sum = 0; for (var i in vals) { sum += vals[i]; } return sum; }
q = function() {
var currentDate = new Date();
currentDate.setDate(currentDate.getDate()-1);
var month = (currentDate.getMonth() < 9 ? "0"+ (currentDate.getMonth()+1) : (currentDate.getMonth()+1));
var day = (currentDate.getDate() < 10 ? "0" + currentDate.getDate() : currentDate.getDate());
var date = currentDate.getTime();
var patt = date;
var query = {"created_at":"2013-30-04 11:19:52.587"};
return query;
}
res = db.logins.mapReduce(m, r, { query : q(), out : "LoginCount" });
As the error says, you can only emit two arguments. One represents the key over which you will be grouping/aggregating values and the other represents the value for this document.
If you need to calculate multiple fields you need to output a single value which is a document. In your example if 1 represents count and date represents some date you can output:
emit(this.cust_id, {count: 1, date: this.date);
This is if you are pulling the date from the document. I'm not sure why you would want to store the date when map was running, but obviously you can include your own date in that field.
Note that when you emit value as a document you must return the exact same format in your reduce function. You can see an example of that here, where they output two different values for each emit and then process both in reduce (you can ignore the finalize function).

Check date range vs. some other date ranges for missing days

Here is what I want to do:
I got a date range from e.g. 03.04.2013 to 23.04.2013 - that's my main range.
Now I have the possibility to create some own time ranges (e.g. 04.04.2013 to 09.04.2013 and 11.04.2013 to 23.04.2013). Those have to cover the whole main range, so every day of the main range (excluding weekens) needs an corresponding day in my own time ranges.
My plan would be to create an Array for the main range. Then I check each day of my own time ranges against the main range. If there is an accordance, I would remove the day from the main range.
So in the end, if everything is ok, there would be an emtpy array, because all days are covered by my own time ranges. If not, then the days not covered would still be in the main range and I could work with them (in this example: 03.04.2013, 10.04.2013)
Does anybody have an better idea to solve this problem? NotesDateTimeRanges?
I would add the dates into a sorted collection and then a "pirate algorithm". Look left, look right and if any of the looks fails you can stop (unless you want to find all missing dates).
Off my head (you might need to massage the final list to store the value back):
var AbsenctSince:NotesDateTime; //Start Date - stored in the NotesItem
var endDate:NotesDateTime; // Return, could be in Notes or Today
var wfDoc:NotesDocument = docApplication.getDocument();
var responseCDs:NotesDocumentCollection = wfDoc.getResponses();
var docResponse:NotesDocument;
var nextResponse:NotesDocument;
//Get the date, which limits the function - if there is a return information, then this is the limit, else today
AbsenctSince = wfDoc.getDateTimeValue("AbsentSince") ;
if (wfDoc.hasItem("ReturnInformationDat")) {
endDate = wfDoc.getDateTimeValue("ReturnInformationDat");
} else {
endDate = session.createDateTime("Today");
}
//Get all days between two dates - as pure Java!
var dateList:java.util.List = getWorkDayList(AbsenctSince.toJavaDate(), endDate.toJavaDate());
// Looping once through the reponse documents
var docResponse = responseCDs.getFirstDocument();
while (docResponse != null) {
nextResponse = responseCDs.getNextDocument(docResponse);
var CDValidSince:NotesDateTime = docResponse.getDateTimeValue("CDValidSince");
var CDValidTill:NotesDateTime = docResponse.getDateTimeValue("CDValidTill");
// Now we need get all days in this range
var removeDates:java.util.List = getWorkDayList(CDValidSince.toJavaDate(),CDValidTill.toJavaDate());
dateList.removeAll(removeDates);
docResponse.recycle();
docResponse = nextResponse;
}
// Both docs are null - nothing to recycle left
// Now we only have uncovered dates left in dateList
docApplication.replaceItemValue("openDates", dateList);
// Cleanup
try {
AbsenctSince.recycle();
endDate.recyle();
wfDoc.recycle();
responseCDs.recycle();
} catch (e) {
dBar.error(e);
}
function getWorkDayList(startDate, endDate) {
var dates:java.util.List = new java.util.ArrayList();
var calendar:java.util.Calendar = new java.util.GregorianCalendar();
calendar.setTime(startDate);
while (calendar.getTime().before(endDate)) {
var workDay = calendar.get(calendar.DAY_OF_WEEK);
if (workDay != calendar.SATURDAY && workDay != calendar.SUNDAY) {
var result = calendar.getTime();
dates.add(result);
}
calendar.add(java.util.Calendar.DATE, 1);
}
return dates;
}
I've done it this way now (seems to work so far):
var dateArray = new Array();
var responseCDs:NotesDocumentCollection = docApplication.getDocument().getResponses();
var dt:NotesDateTime = session.createDateTime("Today");
var wfDoc = docApplication.getDocument();
dt.setNow();
//Get the date, which limits the function - if there is a return information, then this is the limit, else today
var AbsenctSince:NotesDateTime = session.createDateTime(wfDoc.getItemValue("AbsentSince").toString().substr(0,19));
if (wfDoc.hasItem("ReturnInformationDat")) {
var endDate:NotesDateTime = session.createDateTime(wfDoc.getItemValue("ReturnInformationDat").toString().substr(0,19));
} else {
var endDate:NotesDateTime = session.createDateTime("Today");
}
//Get all days between two dates
dateArray = getDates(AbsenctSince, endDate);
for (var i=dateArray.length-1; i >= 0 ; i--) {
var checkDate:NotesDateTime = session.createDateTime(dateArray[i].toString().substr(0,19));
var day = checkDate.toJavaDate().getDay();
//Remove weekends first
if ((day == 6) || (day == 0)) { //6 = Saturday, 0 = Sunday
dBar.info("splice: " + dateArray[i]);
dateArray = dateArray.splice(i,1);
} else {
var docResponse = responseCDs.getFirstDocument();
//Work through all response docs to check if any date is covered
while (docResponse != null) {
var CDValidSince:NotesDateTime = session.createDateTime(docResponse.getItemValue("CDValidSince").toString().substr(0,19));
var CDValidTill:NotesDateTime = session.createDateTime(docResponse.getItemValue("CDValidTill").toString().substr(0,19));
//checkDate covered? If yes, it will be removed
if (checkDate.timeDifference(CDValidSince)/86400 >= 0 && checkDate.timeDifference(CDValidTill)/86400 <= 0 ) {
dBar.info("splice: " + dateArray[i]);
dateArray = dateArray.splice(i,1);
}
docResponse = responseCDs.getNextDocument();
}
}
}
docApplication.replaceItemValue("openDates", dateArray);
And I'm using this function (adopted from this question here):
function getDates(startDate:NotesDateTime, endDate:NotesDateTime) {
var dateArray = new Array();
var currentDate:NotesDateTime = startDate;
while (endDate.timeDifference(currentDate) > 0) {
dateArray.push( currentDate.getDateOnly() );
currentDate.adjustDay(1);
}
return dateArray;
}