Parse date in Ext Js with / as separator - javascript

i am trying to parse a date in Ext JS as follows :
var date = new Date();
date = Ext.Date.parse("2/9/16","n/j/Y");
It creates an instance of the Date but when it tries to parse it, it returns undefined. I dont know where I am going wrong. Can anybody help?

Use y (a two digit representation of a year) instead of Y (a full numeric representation of a year, 4 digits):
Ext.Date.parse("2/9/16","n/j/y")

Try this
var date = Ext.util.Format.date( new Date(), "n/j/Y" );
console.log( date );

var Date = Ext.Date.format(new Date(), 'm/d/Y');

Related

How to add days to javascript unix timestamp? [duplicate]

I want to convert date to timestamp, my input is 26-02-2012. I used
new Date(myDate).getTime();
It says NaN.. Can any one tell how to convert this?
Split the string into its parts and provide them directly to the Date constructor:
Update:
var myDate = "26-02-2012";
myDate = myDate.split("-");
var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]);
console.log(newDate.getTime());
Try this function, it uses the Date.parse() method and doesn't require any custom logic:
function toTimestamp(strDate){
var datum = Date.parse(strDate);
return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));
this refactored code will do it
let toTimestamp = strDate => Date.parse(strDate)
this works on all modern browsers except ie8-
There are two problems here.
First, you can only call getTime on an instance of the date. You need to wrap new Date in brackets or assign it to variable.
Second, you need to pass it a string in a proper format.
Working example:
(new Date("2012-02-26")).getTime();
UPDATE: In case you came here looking for current timestamp
Date.now(); //as suggested by Wilt
or
var date = new Date();
var timestamp = date.getTime();
or simply
new Date().getTime();
/* console.log(new Date().getTime()); */
You need just to reverse your date digit and change - with ,:
new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)
In your case:
var myDate="26-02-2012";
myDate=myDate.split("-");
new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();
P.S. UK locale does not matter here.
To convert (ISO) date to Unix timestamp, I ended up with a timestamp 3 characters longer than needed so my year was somewhere around 50k...
I had to devide it by 1000:
new Date('2012-02-26').getTime() / 1000
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
+ ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
.getSeconds()) : (now.getSeconds())));
}
For those who wants to have readable timestamp in format of, yyyymmddHHMMSS
> (new Date()).toISOString().replace(/[^\d]/g,'') // "20190220044724404"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220"
Usage example: a backup file extension. /my/path/my.file.js.20190220
Your string isn't in a format that the Date object is specified to handle. You'll have to parse it yourself, use a date parsing library like MomentJS or the older (and not currently maintained, as far as I can tell) DateJS, or massage it into the correct format (e.g., 2012-02-29) before asking Date to parse it.
Why you're getting NaN: When you ask new Date(...) to handle an invalid string, it returns a Date object which is set to an invalid date (new Date("29-02-2012").toString() returns "Invalid date"). Calling getTime() on a date object in this state returns NaN.
JUST A REMINDER
Date.parse("2022-08-04T04:02:10.909Z")
1659585730909
Date.parse(new Date("2022-08-04T04:02:10.909Z"))
1659585730000
/**
* Date to timestamp
* #param string template
* #param string date
* #return string
* #example datetotime("d-m-Y", "26-02-2012") return 1330207200000
*/
function datetotime(template, date){
date = date.split( template[1] );
template = template.split( template[1] );
date = date[ template.indexOf('m') ]
+ "/" + date[ template.indexOf('d') ]
+ "/" + date[ template.indexOf('Y') ];
return (new Date(date).getTime());
}
The below code will convert the current date into the timestamp.
var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);
The first answer is fine however Using react typescript would complain because of split('')
for me the method tha worked better was.
parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))
Happy to help.
In some cases, it appears that some dates are stubborn, that is, even with a date format, like "2022-06-29 15:16:21", you still get null or NaN. I got to resolve mine by including a "T" in the empty space, that is:
const inputDate = "2022-06-29 15:16:21";
const newInputDate = inputDate.replace(" ", "T");
const timeStamp = new Date(newInputDate).getTime();
And this worked fine for me! Cheers!
It should have been in this standard date format YYYY-MM-DD, to use below equation. You may have time along with example: 2020-04-24 16:51:56 or 2020-04-24T16:51:56+05:30. It will work fine but date format should like this YYYY-MM-DD only.
var myDate = "2020-04-24";
var timestamp = +new Date(myDate)
You can use valueOf method
new Date().valueOf()
a picture speaks a thousand words :)
Here I am converting the current date to timestamp and then I take the timestamp and convert it to the current date back, with us showing how to convert date to timestamp and timestamp to date.
The simplest and accurate way would be to add the unary operator before the date
console.log(`Time stamp is: ${Number(+new Date())}`)
Answers have been provided by other developers but in my own way, you can do this on the fly without creating any user defined function as follows:
var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000
Simply performing some arithmetic on a Date object will return the timestamp as a number. This is useful for compact notation. I find this is the easiest way to remember, as the method also works for converting numbers cast as string types back to number types.
let d = new Date();
console.log(d, d * 1);
This would do the trick if you need to add time also
new Date('2021-07-22 07:47:05.842442+00').getTime()
This would also work without Time
new Date('2021-07-22 07:47:05.842442+00').getTime()
This would also work but it won't Accept Time
new Date('2021/07/22').getTime()
And Lastly if all did not work use this
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Note for Month it the count starts at 0 so Jan === 0 and Dec === 11
+new Date(myDate)
this should convert myDate to timeStamp

convert string to UTC time using jquery

I am trying to convert string to time, the string i have are in this format, '8:3' and '16:45'.
I want to convert UTC time in jQuery.
You can write your function to create UTC date with the time string.
function toUTC(str) {
let [h, m] = str.split(':');
let date = new Date();
date.setHours(h, m, 0)
return date.toUTCString();
}
console.log(toUTC('8:3'))
console.log(toUTC('16:45'))
You don't need jQuery for such operations. Just the simple Date object will do the trick. Say you want to convert time from a specific date.
let date = new Date('2020-04-01'); // leave the Date parameter blank if today
date.setHours(16); // must be 24 hours format
date.setMinutes(45);
let theUTCFormat = date.getUTCDate();
Cheers,

Parse dates from Javascript Date Object to regular datetime

How do I convert a date from JS Date Object to php datetime?
The following dates were converted to a Javascript Date Object from php datetimes:
"startsAt": "2015-08-15T10:46:00+00:00",
"endsAt": "2015-08-15T11:46:00+00:00"
converted using this syntax in javascript:
for (var i = 0; i < events.events.length; i++) {
events.events[i].startsAt = new Date(events.events[i].startsAt);
events.events[i].endsAt = new Date(events.events[i].endsAt);
}
startsAt and EndsAt looked like so after the conversion:
startsAt: Date 2015-08-15T11:46:00.000Z
endsAt: Date 2015-08-15T11:46:00.000Z
Now my goal is to do the opposite in javascript (angularjs): Convert from Javascript Date Object to php datetime 2015-08-15T10:46:00+00:00. Any idea would help. Thanks
Just to fix correct an answer below:
var rawDate = new Date();
var parsedDate = [
rawDate.getDate(),
(rawDate.getMonth() + 1), //because getMonth() starts from 0
rawDate.getFullYear()
].join('-');
console.log(parsedDate); // output could be: 19-08-2015 for example
or just call any of the following to convert date object to string:
rawDate.toJSON();
rawDate.toISOString();
You've got to parse it manually doing something like:
var rawDate = new Date();
var parsedDate = rawDate.getDate() + '-' + rawDate.getMonth() + '-' + rawDate.getFullYear();
console.log(parsedDate); // output could be: 19-08-2015 for example
Other possible ways of doing this could be found in here.

Javascript convert dates

I am getting this "20131218" date/time value from an API result.
What I want to do is convert this date into something like this "2013-12-18". I know this is very easy in PHP by simply doing this code:
echo date("Y-m-d",strtotime('20131218'));
output: 2013-12-18
This is what I tried in javascript:
var myDate = new Date("20131218");
console.log(myDate);
But the output is Date{ Invalid Date } so obviously this is wrong.
My question here what is the equivalent of strtotime in javascript? or if there's no equivalent, how would I convert this value as my expected result(2013-12-18) using javascript?
Your help will be greatly appreciated!
Thanks! :)
The value is invalid to convert it to date. So either from your PHP code send it as a proper format like 20131218
Or convert the value you get in your Javascript to similar kind of format.
var dateVal="20131218";
/*
// If it's number ******* //
var numdate=20131218;
var dateVal=numdate.toString();
*/
var year=dateVal.substring(0,4);
var mnth=dateVal.substring(4,6);
var day=dateVal.substring(6,8);
var dateString=year+"-"+mnth+"-"+day;
var actualDate = new Date(dateString);
alert(actualDate);
JSFIDDLE DEMO
Javascript has a Date.parse method but the string you have is not suitable to pass to it. You don't really need to create a date object just to format a string. Consider:
function formatDateStr(s) {
s = s.match(/\d\d/g);
return s[0] + s[1] + '-' + s[2] + '-' + s[3];
}
alert(formatDateStr('20131218')); // '2013-12-18'
If you wish to convert it to a date object, then:
function parseDateStr(s) {
s = s.match(/\d\d/g);
return new Date(s[0] + s[1], --s[2], s[3]);
}
The reason why it is showing Invalid date is, it wants it to be in format
Following format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS
If you breakdown your string using following format just add dash at relevant places then you are good to go and use newDate.
1. var myDate = new Date("2013-12-18");
alert(myDate);
2. var myDate = new Date(2013,12,18);
Eventually you can modify your string manipulate it and use it in aforementioned format.

jQuery how can you verify date formatted mm/dd/yyyy is not greater than current date today

How do I verify in jQuery that a date entered on a input text box or value in html such as mm/dd/yyyy is not greater than todays date. Example would be "5/5/2011" would pass as true b/c its not greater than today "6/17/2011", but "5/5/3011" would be greater than today and should return false. Is there a simple function that can return true or false if a date in form "mm/dd/yyyy" is greater than todays date in javascript or jQuery?
Just convert to a Date object and compare your date value to Date.now - for example:
alert( Date.parse("3/1/2012") > Date.now())
You do not actually need to use jQuery for this at all, pure JavaScript is good enough. Please have a look at the docs for Javascript Date for more information.
convert to javascript Date objects to compare.
var d = new Date("5/5/2011")
var d2 = new Date()
var b = d < d2 // << true...
First off, you need to be sure that dates have a universal format. 10/1/2011 is in the future in the US (October 1st, 2011) but in the past in the UK (10th January 2011). If that's satisfied, the below will work just fine:
function greaterThanToday(datestring) {
var today = new Date();
var date = new Date(datestring);
return (date > today);
}
alert("5/5/2011: " + greaterThanToday("5/5/2011"));
alert("5/5/3011: " + greaterThanToday("5/5/3011"));
Don't even need jQuery, just Date objects.
Date.parse("6/17/2011") > Date.parse("5/5/3011")

Categories

Resources