EXTJS date calculation - javascript

I have "startdate" field, that I'm getting its value. Plus I have three other fields: day,month,year. Which I'm also getting its values. Now I have to add day and month and year to startdate to get my new date. Can anybody help me with this, in order to maintain date conditions? e.g: so i don't add 12 days to 25 and get 37.
function calDate(){
var startDate;
var trs_jour = Ext.getCmp('JOUR').getValue();
var trs_mois = Ext.getCmp('MOIS').getValue();
var trs_annee = Ext.getCmp('ANNEE').getValue();
if(trs_jour!='' || trs_mois!='' || trs_annee!=''){
var d = new Date(Ext.getCmp('STARTDATE').getValue());
var year = d.getFullYear();
var month = d.getMonth()+1;
var day = d.getDate();
}

Ext.Date class defines some basic methods for handling dates.
Provides a convenient method for performing basic date arithmetic. This method does not modify the Date instance being called - it creates and returns a new Date instance containing the resulting date value.
Ext.Date.add ( date , interval , value )
PARAMETERS
date : Date
The date to modify
interval : String
A valid date interval enum value.
value : Number
The amount to add to the current date.
RETURNS : Date
The new Date instance.
Examples :
// Basic usage:
var dt = Ext.Date.add(new Date('10/29/2006'), Ext.Date.DAY, 5);
console.log(dt); // returns 'Fri Nov 03 2006 00:00:00'
// Negative values will be subtracted:
var dt2 = Ext.Date.add(new Date('10/1/2006'), Ext.Date.DAY, -5);
console.log(dt2); // returns 'Tue Sep 26 2006 00:00:00'

Related

How to add today's time to any date object and getISOString?

I have a ngbDatePicker which helps me to pick a date. Then it returns an object like this:
{year:2020,month:12,day:03}
I'd like to get an ISOString of this date with today's time(current). So if time is 18:42 I should be able to get something like this:
2020-12-03T18:42:00.000Z
To do that I parsed object and made date firstly
(model is the object holds date like above)
var date = new Date(this.model.year + "-" + this.model.month + "-" + this.model.day);
//then to add today's time I found solution below on the internet whcih didn't work for me
var date2 = new Date(date);
var isoDateTime = new Date(date2 .getTime() - (date2 .getTimezoneOffset() * 60000)).toISOString();
Here isoDateTime returns 2020-12-10T03:00:00.000Z which is not I want.
How to solve this?
Working stackblitz
Just take the time part of a Date object and combine it with this.model:
var date2 = new Date();
var date = new Date(this.model.year, this.model.month-1, this.model.day,
date2.getHours(), date2.getMinutes(), date2.getSeconds());
var isoDateTime = date.toISOString();
console.log(isoDateTime);
The month parameter is 0 based, so we have to substract 1 from the month.
Result (I chose Dec.1st 2020 in the Datepicker):
2020-12-01T19:22:42.000Z
Try on Stackblitz
You can create a single Date for the time and append it to values from the object:
function myISOString(obj) {
let z = n=>('0'+n).slice(-2);
return `${obj.year}-${z(obj.month)}-${z(obj.day)}T${new Date().toTimeString().substring(0,8)}`;
}
let obj = {year:2020, month:12, day: 3};
console.log(myISOString(obj));
PS the use of leading zeros like 03 for numbers should be avoided as once upon a time that notation indicated octal values (but not any more), so 09 might be confusing.

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!');
}

Subtracting Date time value

I have the upload date for a course saved in a ViewModel variable #Model.Course.UploadDate when calling the following code:
alert('#Model.Course.UploadDate');
I get an output as expected of:
21/01/2014 16:16:13
I know want to check that the uploadDate is within the last 10 seconds before sending a statement to the database but trying to use the following code:
var uploadDate = new Date('#Model.Course.UploadDate.ToLongDateString()');
alert("UPLOAD DATE " + uploadDate);
I get an unexpected output of:
Tue Jan 21 2013 00:00:00 GMT+0000
This is the format that I need the date in only with the saved time data shown. I am then looking to perform a calculation as follows:
var TENSECONDS = 10 * 1000;
var uploadDate = new Date('#Model.Course.UploadDate.ToLongDateString()');
var today = new Date();
var check = today - uploadDate;
if (parseInt(check) > parseInt(TENSECONDS))
alert("ROUTE1");
else
alert("ROUTE2");
Quote from the documentation of the Date object constructor:
value: Integer value representing the number of milliseconds since 1
January 1970 00:00:00 UTC (Unix Epoch).
So actually that's the safest thing to pass to the constructor of a Date object instead of some strings which might be incorrectly interpreted and are completely culture dependent.
So just convert your DateTime instance to the number of milliseconds that elapsed since 1 January 1970 and feed this timestamp to the constructor:
var timestamp = #(Model.Course.UploadDate - new DateTime(1970, 1, 1)).TotalSeconds;
var uploadDate = new Date(timestamp);
As an alternative you could use the ISO8601 format if you intend to be passing a string:
dateString: String value representing a date. The string should be in
a format recognized by the Date.parse() method (IETF-compliant RFC
2822 timestamps and also a version of ISO8601).
So:
var uploadDate = new Date('#Model.Course.UploadDate.ToString("o")');
I solved this using the following code:
var dateArray = new Array();
dateArray = '#Model.Course.UploadDate'.split("/");
var dateD = dateArray[0];
var dateM = dateArray[1];
var dateY = dateArray[2];
var dateT = dateArray[3];
timeArray = dateT.split(":");
var timeH = timeArray[0];
var timeM = timeArray[1];
var timeS = timeArray[2];
var dateUS = dateM + "/" + dateD + "/" + dateY + dateT;
var uploadDate = new Date(dateD,dateM,dateY,timeH,timeM,timeS);

convert custom date string to date object

How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);

Acrobat Javascript Dates

I have a text field that displays the date in mmmm d, yyyy (called 'Expiry Date') and I am trying to make three smaller fields that display just the day (d), the month (m), and the year (yyyy) in each field.
I have tried to import the data into each field using this code:
var sField = 'Expiry Date'
and then i would custom format it just to "d", "m", or "yyyy" as appropriate. In the little formatting preview window it would show the desired output, but the fields would still be blank.
What is also odd is that it will only work with formatting that starts with the month.
The field that Im getting the first date is created from another calculation if that makes it any different. 'Expiry Date' gets it's data from a field called 'date'. Here is the code in which it assigns an expiry date 30 days after the value of 'date'
// define the value for the date field
var sField = 'Date'
// define the format of the date string
var cFormatDate = 'mm/dd/yyyy';
// define some time constants
var fSecond = 1000; // number of milliseconds in one second
var fMinute = 60 * fSecond; // number of milliseconds in a minute
var fHour = 60 * fMinute; // number of milliseconds in an hour
var fDay = 24 * fHour; //number of milliseconds in a day
// get the field object's string value
var fTodayDate = this.getField(sField).value;
// convert the string value into a date object
var oDate = util.scand(cFormatDate, fTodayDate);
// convert the date object to a value in milliseconds
var fDate = oDate.getTime();
// add 30 days to value using the number of milliseconds in a day
var fNewDate = fDate + (30 * fDay);
// convert computed date value to date object
var oNewDate = new Date(fNewDate);
// set the field's value to the date string for the date object
event.value = util.printd(cFormatDate, oNewDate);
Thanks in advance!!
I don't know anything about Acrobat, but assume its Date objects conform to ECMA-262. By far the best method of converting a date string to a date object is to parse it yourself, do not leave it up to the Date function/constructor or Date.parse.
From your post, it seems the date string is like October 17, 2012. There's a function below to help with that.
The best way to add whole days is to add them to the date, so given a date object:
// Create a new Date object
var now = new Date();
// Copy it
var then = new Date(now);
// Add 30 days
then.setDate(then.getDate() + 30);
Note that adding 30 to dates after 28 January (or 29 January in a leap year) will end up in March.
Edit
Date string parse function:
// Expects mmm d, yyyy e.g. October 17, 2012 or Oct 17, 2012
function parseDateString(s) {
var months={jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
var d = s.split(/\s/);
return new Date(d[2], months[d[0].toLowerCase().substring(0,3)], parseInt(d[1],10));
}
I may be over simplifying things, but if you have a date field (let's name it "DATE1") that has the full date in it.
Couldn't you just copy that field 3 time, assigning "DATE1" to the name for all three. This would take the date that you typed into the original Date field and duplicate it throughout the other three. Then just go into the field properties, ensure all 4 boxes are assigned the format "Date" -- and then on your 3 smaller boxes, assign them a Custom Date Option of "dd", "mm", or "yy" respectively?

Categories