Subtracting Date time value - javascript

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);

Related

EXTJS date calculation

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'

How can I get a string date in the format "2016-07-06T10:57Z" from Date() and toISOString

I need to get a date in this format:
2016-07-06T10:57Z
Using this code I have been able to get a date in a format somewhat like I need:
var isoDate = new Date().toISOString();
2016-07-06T08:46:08.127Z
But is there a way I can remove the seconds and fraction of seconds from the date so it appears exactly like the date: "2016-07-06T10:57Z" ?
You will always want to remove the last 8 characters ('Z' included) thus you can use a function like slice
isoDate = isoDate.slice(0, -8); //Remove seconds + fractions + Z
isoDate += "Z"; //Add back the Z
You can use this way because the format returned by toISOString() will always be
YYYY-MM-DDTHH:mm:ss.sssZ
Please try
var isoDate = new Date().toISOString();
var pos = isoDate.lastIndexOf(':');
var datePart1 = isoDate.substring(0,pos);
var datePart2 = isoDate.substr(-1, 1);
var dateStr = datePart1+datePart2;
console.log(dateStr);

Invalid date - Number to Date

I was trying to convert a Number to Date in Javascript. Below is the code which I have tried
var newDate = new Date(1012256900000);
console.log("Test: ",newDate.toString('MMM-yyyy'));
This is working fine.
But when I get it from $rootScope object, am getting invalid date :(
var newDate = new Date($rootScope.lastLoginTime);
console.log("Test: ",newDate.toString('MMM-yyyy'));
This is printing Invalid Date. FYI,
$rootScope.lastLoginTime = 1463256900000;
Gonna take a guess here, but look at what I did in the browser console:
new Date(1463256900000)
> [date] Sat May 14 2016 21:15:00 GMT+0100
new Date("1463256900000")
> [date] Invalid date
Completely wild guess, but perhaps you should ensure you are passing a number, not a string, to new Date() - the constructor behaves very differently in either case.
Consider instead trying this:
var newDate = new Date();
newDate.setTime($rootScope.lastLoginTime);
setTime takes a numeric argument only, and will convert your string to a number for you if you pass it one.
Guess your $rootScope.lastLoginTime = '1463256900000'; than $rootScope.lastLoginTime = 1463256900000;.
new Date(time) does works when time is number , not when time is string.
var t1 = 1463256900000;
var t2 = '1463256900000';
var d1 = new Date(t1);
var d2 = new Date(t2);
console.info(d1);
console.info(d2);

Convert UTC to standard date time format using javascript

How can I convert a UTC time into proper date - time format using Javascript?
This is what I want to do
var d = new Date("2014-01-01");
var new_d = d.toUTC(); // 1388534400000
var old_d = function(new_d){
// return "2014-01-01" // how can i get this?
}
Now How, can i get orignal date - 2014-01-01 from 1388534400000?
****Also, Please note that when i do this --- new Date(1388534400000); it gives date 1 day less.
That is, instead of giving Jan 01 2014, it gives Dec 31 2013. But, I want Jan 01 2014.****
Is there any method to do the opposite of toUTC() method?
// _________ For those whose toUTC() doesnt work
"toUTC" method works in console of my chrome
See screen shot below
When you pass a string containing hyphens to the Date constructor, it will treat that as UTC. And if you don't pass a time, it will consider it to be midnight. If you are in a time zone that is behind UTC (such as in most of the Americas), you will see the wrong local time conversion.
Here's a screenshot of my chrome dev console, so you can see what I mean
If I pass slashes instead:
Consider using moment.js - which will accept a format parameter that will help you avoid this issue.
Try using the following:
new Date(new_d);
The problem lies with the way you instantiate the Date.
Javascript interpretes the hyphens as an utc date, and slashes as local dates.
Giving the results that mark Explains.
var utcDate = new Date('2014-01-01') // returns a UTC date
var localDate = new Date('2014/01/01'); // Returns local date
But to translate a date back to your starting point string, you can do the following.
function toDateString(utcMillis){
var date = new Date(utcMillis);
d = date.getDate();
m = date.getMonth() +1;
y = date.getFullYear();
return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}
function addLeadingZero(n, length){
n = n+'';
if(n.length<length)
return addLeadingZero('0'+n, length--);
else
return n;
}
If you find yourself with a UTC date, you can still do this:
function toUTCDateString(utcMillis){
var date = new Date(utcMillis);
d = date.getUTCDate();
m = date.getUTCMonth() +1;
y = date.getUTCFullYear();
return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}
To play around with it, and see it for yourself, see this Fiddle:

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);

Categories