I used the following function:
function datediff()
{
var dat1 = document.getElementById('date1').value;
alert(dat1);//i get 2010-04-01
var dat2 = document.getElementById('date2').value;
alert(dat2);// i get 2010-04-13
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((dat1.getTime() - dat2.getTime())/(oneDay));
alert(diffDays);
}
I get the error:
dat1.getTime()` is not a function
That's because your dat1 and dat2 variables are just strings.
You should parse them to get a Date object, for that format I always use the following function:
// parse a date in yyyy-mm-dd format
function parseDate(input) {
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
I use this function because the Date.parse(string) (or new Date(string)) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.
For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.
I was facing this error because I tried to compare two dates using the following Method
var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator
However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.
Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime() method was simply not added to the prototype.
Solution
In this case, recreating a date-Object based on your dates will fix the issue.
var res = new Date(dat1).getTime() > new Date(dat2).getTime()
Edit:
I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.
The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.
class Details {
description: string;
date: Date;
score: number;
approved: boolean;
constructor(data: any) {
Object.assign(this, data);
}
}
and to perform the mapping:
public getDetails(id: number): Promise<Details> {
return this.http
.get<Details>(`${this.baseUrl}/api/details/${id}`)
.map(response => new Details(response.json()))
.toPromise();
}
for arrays use:
public getDetails(): Promise<Details[]> {
return this.http
.get<Details>(`${this.baseUrl}/api/details`)
.map(response => {
const array = JSON.parse(response.json()) as any[];
const details = array.map(data => new Details(data));
return details;
})
.toPromise();
}
For credits and further information about this topic follow the link.
To use this function/method,you need an instance of the class Date .
This method is always used in conjunction with a Date object.
See the code below :
var d = new Date();
d.getTime();
Link : http://www.w3schools.com/jsref/jsref_getTime.asp
dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp
You would use it like this:
var date = Date.parse(dat1);
It's a time format problem
change it by following.
Date.parse(dat1)
instead of
dat1.getTime()
You could conditionally check if the value is a Date object in the following way.
const d1 = new Date();
if (typeof d1 === 'object' && d1 !== null && 'getTime' in d1) {
const result = d1.getTime();
console.log(result); // 👉️ 163966...
}
https://bobbyhadz.com/blog/javascript-typeerror-date-gettime-is-not-a-function
Related
I want to compare last 30 mins data and display in UI. Datetime needs be UTC. I tried using Moment but i am getting error
Javascript - Operator '>' cannot be applied to types 'Date' and 'Moment'.
Below is my code :
let d = moment();
let d_utc = moment.utc();
var customDate = new Date();
d_utc.minutes(-30);
filteredData = filteredData.filter((category) => {
return category.uploaded_time > d_utc;
});
If you wish to compare a Date to an instance of a Moment with a Date, you need to convert them both to the same date.
You can call .toDate() to convert a moment to a Date or moment(date) to convert a Date to a Moment.
return category.uploaded_time > d_utc.toDate()
JavaScript doesn't have operator overrides, so the safest way to compare Moments is using diff:
return moment(category.uploaded_time).diff(d_utc) > 0
At the documentation in get+set section you can compare the seconds
Examplet in documentation
moment.utc().seconds(30).valueOf() === new Date().setUTCSeconds(30);
Your code should be
let d_utc = moment.utc();
let d_utc = moment.utc().minutes(-30).valueOf();
filteredData = filteredData.filter((category) => {
return category.uploaded_time.getUTCSeconds() > d_utc;
});
Also there is a query section you can check it
I expect to get a date from my database in Ymd format.
This gives me values like 20200202. This is fine for php applications but I'm using JavaScript for the frontend.
In php, we could do something like
$date = DateTime::createFromFormat('Ymd', '20200202');
meaning I get a date object as long as the formats match.
Is there a way for JavaScript to do this?
If you are sure this date will always come in the format yyyymmdd, you can use RegEx to extract the date :
function getDate(inputDate)
{
// TODO : Check if the format is valid
const pattern = /(\d{4})(\d{2})(\d{2})/
const parts = inputDate.match(pattern);
// months start with 0 in js, that's why you need to substract 1
// -----------------------v----------v
return new Date(parts[1], parts[2] - 1, parts[3]);
}
console.log(getDate("20200202").toString());
console.log(getDate("20200213").toString());
console.log(getDate("20201231").toString());
You could always check if the format matches your requirements and then split the value you get from the database. Then you could either return a Boolean value false if not possible or a date.
const dbOutput = '20200202';
const createdDate = getDate(dbOutput);
function getDate(value) {
if(value.length !== 8) {
return false;
}
const year = +value.substring(0,4);
const month = +value.substring(4,6);
const day = +value.substring(6,8);
try {
return new Date(year, month-1, day);
} catch (error) {
return false;
}
}
In Chrome you can do:
date = new Date();
and then in the console you can do:
hour:date.getHours();
What is this called? Where else does it work?
I saw this in the follow code:
showDateTimePicker(date, callback) {
date = date || new Date();
var options = {
...this.props,
year:date.getFullYear(),
month:date.getMonth(),
day:date.getDate(),
hour:date.getHours(),
minute:date.getMinutes()
};
RCTDateTimePicker.showDateTimePicker(options, function (year, month, day, hour, minute) {
date.setFullYear(year);
date.setMonth(month);
date.setDate(day);
date.setHours(hour);
date.setMinutes(minute);
callback(date);
});
}
hour:date.getHours(); and var options = {hour:date.getHours()}; are two very different statements.
The former is a label which is designed so that when you have nested loops and want to break or continue from one of them, you can specify which. Putting it before a function call is useless.
The latter is an object initialiser which allows you to specify the name and values of properties on a new object.
I am trying to deserialize a json object that has a javascript date in it. When JSON.stringify is called on the object, dates are serialized to strings that are not properly deserialized back to dates. I have attempted to deserialize the object using both the native browser implementation with chrome, IE, and FF and using jquery. Both give the some results. Here is the snippet:
var obj = {Date: new Date()};
var objSer = JSON.stringify(obj);
var objDeser = JSON.parse(objSer);
var objJqDeser = $.parseJSON(objSer);
function getYear(value){
try{
return value.getYear();
}
catch(err){
return err;
}
}
$("#orig").text("Orig Year: " + getYear(obj.Date));
$("#deser").text("Deser Year: " + getYear(objDeser.Date));
$("#jqDeser").text("JqDeser Year: " + getYear(objJqDeser.Date));
I want objDeser.Date to be a js date not a string. You can see this problem in action here: http://jsbin.com/unijud/24/edit. Is there any js libraries that can properly deserialize the dates when building the javascript object?
JSON.parse has a little-known second parameter: the 'reviver' function. This is used for precisely this purpose: to revive a date string into a Date object (or, hypothetically, any other kind of object you wanted to convert from string) during the initial parse.
There's an SO post about this, and here's a blog post that includes an implementation example and a function that will do property checking for a couple common date encodings (ISO & that weird .NET AJAX format), before parsing to a Date.
Here's the key function from that blog post, fwiw:
// JSON date deserializer
// use as the second, 'reviver' argument to JSON.parse();
if (window.JSON && !window.JSON.dateParser) {
var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*))(?:Z|(\+|-)([\d|:]*))?$/;
var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/;
JSON.dateParser = function (key, value) {
// first, just make sure the property is a string:
if (typeof value === 'string') {
// then, use regex to see if it's an ISO-formatted string
var a = reISO.exec(value);
if (a) {
// if so, Date() can parse it:
return new Date(value);
}
// otherwise, see if it's a wacky Microsoft-format string:
a = reMsAjax.exec(value);
if (a) {
// and perform some jujitsu to make use of it:
var b = a[1].split(/[-+,.]/);
return new Date(b[0] ? +b[0] : 0 - +b[1]);
}
// here, you could insert any additional tests and parse instructions you like, for other date syntaxes...
}
// important: you need to return any values you're not parsing, or they die...
return value;
};
}
// use: JSON.parse(json,JSON.dateParser);
(There are lots of opinions about proper regexes for ISO 8601 dates. YMMV. Also, there's no particular reason to punch the function onto the global JSON object. You could store/reference it anywhere you like. )
I took #LastCoder advice and wrote a simple implementation. It seems to be doing what I wanted it to.
var jsonDates = {
dtrx2: /\d{4}-\d{2}-\d{2}/,
parse: function(obj){
var parsedObj = JSON.parse(obj);
return this.parseDates(parsedObj);
},
parseDates: function(obj){
// iterate properties
for(pName in obj){
// make sure the property is 'truthy'
if (obj[pName]){
var value = obj[pName];
// determine if the property is an array
if (Array.isArray(value)){
for(var ii = 0; ii < value.length; ii++){
this.parseDates(value[ii]);
}
}
// determine if the property is an object
else if (typeof(value) == "object"){
this.parseDates(value);
}
// determine if the property is a string containing a date
else if (typeof(value) == "string" && this.dtrx2.test(value)){
// parse and replace
obj[pName] = new Date(obj[pName]);
}
}
}
return obj;
}
};
A live example is available on jsbin. A reference is available on gist.
In order to represent dates using JavaScript, I found that JSON uses ISO 8601, a specific string format to encode dates as string. When I last checked though, there is not an official standard for what the date format should look like. The major browsers use ISO 8601 as the JSON Date encoding format.
So, dates are encoded as ISO 8601 strings and then used just like a regular strings when the JSON is serialized and deserialized.
That being said, ISO dates can be converted into JavaScript dates by use of the JavaScript Date constructor, which accepts a wide variety of inputs to construct a date, ISO 8601 being one of them.
Get todays date:
var curDate = new Date();
document.write(curDate); //Mon Feb 01 2016 12:57:12 GMT-0600 (Central Standard Time)
Parse it into a string:
var dateStr = JSON.parse(JSON.stringify(curDate));
document.write(dateStr);//2016-02-01T18:59:35.375Z
Then convert it back to a javascript date, using the constructor:
var date = new Date(dateStr);
document.write(date); //Mon Feb 01 2016 12:59:35 GMT-0600 (Central Standard Time)
The JSON spec does not include special formatting for dates. As such they are often serialized as a string, sometimes with special markings to indicate it should be treated as a Date object if the language supports them. As such, most (all?) browser-native JSON parsers can not round-trip a Date object properly.
There are several good libraries that help with this - I very much like MomentJS though I have used datejs in the past as well. You would just need to iterate over your objects and convert the proper fields to Date objects after they have been parsed.
I find it helpful to remember that the JSON format is much more restrictive than JavaScript object literal notation.
The JavaScript es5 is able to parse the date like 2018-04-03T22:00:00... in its default Date constructor. (e.g. new Date("2018-04-03T22:00:00...");.
For someone like me, who is searching for automatic date deserialization from JSON web responses, this could be handy.
/**
* Iterates over all entries of the input object and replace the string dates with the objects of {#link Date}.
*/
function fixDateObjects(responseBody) {
if (responseBody) {
const regex = /^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}/;
for (const [key, value] of Object.entries(responseBody)) {
const val = String(value);
if (val.startsWith('[object Object]')) {
fixDateObjects(value);
}
if (val.match(regex)) {
responseBody[key] = new Date(val);
}
}
}
}
Explanation: It iterates over all object entries of the JSON(responseBody) and replaces the string dates (matched by the given regex) with the new Date(str) objects.
Result: This brings you freedom of further processing. Now you have all date strings fully deserialized.
//usage
function parseBody(response) {
fixDateObjects(response);
console.log(response.someDate); // Mon Aug 30 2021 22:45:59 GMT+0200 (...)
// further processing
}
You could manually add all of the Date functions you require to the String.prototype.
String.prototype.getYear = function() {
return Date.parse(this).getYear();
};
var obj = {date: new Date()};
var dtObj = JSON.parse(JSON.stringify(obj));
console.log(dtObj.date.getYear());
Or you could override JSON.parse and have it loop through the result object looking for strings that match the time stamp regex and then convert them to Date objects.
var JSON_parse = JSON.parse;
JSON.parse = function(str) {
var res = JSON_parse(str);
findAndConvertStringsToDates(res);
return res;
}
EDIT Here's what I'd throw together for an implementation
(function() {
var jsonParse = JSON.parse;
var reDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/i;
function jsonDate(obj) {
var type = typeof(obj);
if(type == 'object') {
for(var p in obj)
if(obj.hasOwnProperty(p))
obj[p] = jsonDate(obj[p]);
return obj;
} else if(type == 'string' && reDate.test(obj)) {
return new Date(obj);
}
return obj;
}
JSON.parse = function(str) { return jsonDate(jsonParse(str)); }
})();
/*
* Tests
*/
var dt = JSON.parse(JSON.stringify({date: new Date()}));
console.log(typeof(dt.date));
console.log(JSON.parse(JSON.stringify(null)));
console.log(JSON.parse(JSON.stringify(123)));
console.log(JSON.parse(JSON.stringify("test")));
console.log(JSON.parse(JSON.stringify(new Date())));
console.log(JSON.parse(JSON.stringify([1,new Date(),2])));
console.log(JSON.parse(JSON.stringify({d: new Date(), d2: {d3: new Date(), d4: [0,new Date(),4]}})));
Is there a way to take a date object from a HTML object in the format of ####-##-## and convert it to epoch time. For example, the user inputs the value of August 12, 2012 which shows as 2012-08-12 when I print out the .val() of it, and I need to get this in Epoch time.
EDIT
Code to date:
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
console.log($("#hv-start-date").val()); // => 2012-08-20
hvStartDate = new Date($("#hv-start-date").val()).getTime(); // => NaN
}
if (hvEndDate == "") {
hvEndDate = "end"
}
else {
hvEndDate = new Date($("#hv-end-date").val()).getTime(); // => NaN
}
var myTmp = new Date("2012-08-20");
console.log(myTmp.getTime()); // => NaN
Javascript's Date built-in allows you to pass a date string into its constructor, giving you a Date based on that string. From there, calling getTime( ) will give you the epoch time.
new Date($('.user-value').val()).getTime(); // => epoch time
new Date('2012-08-12').getTime(); // 1344729600000
Caveat: Beware of locale strings and locale-specific date formatting (for example, the position of days and months switch depending on locale).
EDIT: Based on your code in the comment below, here's what you need to do. Notice that you have to instantiate a new Date Object before calling getTime():
if (hvStartDate == "") {
hvStartDate = "start"
}
else {
hvStartDate = new Date($("#hv-start-date").val()).getTime();
}
Simply use the getTime() function. It returns the number of milliseconds since Epoch :
var msSinceEpoch = myDate.getTime();
Complete Date reference at MDN : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
EDIT : if you have to parse it too, you may :
use new Date(theString) if it has the good format
set yourself the different date fields (see reference) after having parsed it
use a date parsing library. I use this one : http://www.datejs.com/ which is very powerful for all date parsing, computing and formating.