Cannot find function getMonth in Object 05/06/11 - javascript

Why do i get this error, when i format my date? Code follows below
var date = /Date(1306348200000)/
function dateToString(date) {
return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getYear();
}
function dateFromString(str) {
return new Date(str);
}

You define var date as a regular which can not be accepted by new Date,just do it like this.
var date = 1312711261103;
try it like this: http://jsfiddle.net/zhiyelee/wLNSS/

In your code, date is a regular expression, not a Date object. You probably want:
var date = new Date(1306348200000);
Also note that calling date Date without new returns a string and not a Date object.
Edit: Apparently I overlooked the dateFromString function, but your code does not show what you do with date and how you use these functions. Anyway, it should be clear which value you have to pass to Date. Definitely not a regular expression.

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

Date formatting in google-script

I want to change the format to "mmm-dd-yyyy"(Nov-11-2019) using the code that I have.
Please see below code:
var timeStamp = data[i][timeStampappr];
var formatted = (timeStamp.getMonth()+1) + '/' + timeStamp.getDate() + '/' + timeStamp.getYear();
Current format is 11/11/2019 and I want it to be like Nov-11-2019
If you use the following, then if timestamp is a string it might be of a form that the date constructor will create the date properly. If it's a date the it just creates another date object with the same value. So If you're not always sure what you're going to find in your timestamp value this approach may provide you with more consistent performance. Also note the M's have to be capitalize for the Month.
Utilities.formatDate(new Date(timestamp), Session.getScriptTimeZone(), "MM-dd-yyyy");
Simple Date Formatting Reference
JavaScript Date Constructor
Great question, a straight-forward solution if you can't find a more specific function to do the job, is to create an array of the string representation of the months. That is:
var monthsAsStrings = ["Jan", "Feb", "Mar", ... ];
var formatted = monthsAsStrings[timeStamp.getMonth() + 0 ] + '-' + timeStamp.getDate() + '-' + timeStamp.getYear();
^ ^ ^
Note that array indices start at 0, while we typically call January month 1. The + 0 is not necessary but illustrates the difference between the code you posted and what you're requesting.
Additionally, the '/' is replaced with '-'.
In this way, you could check first if you have a timestamp, before formatting the date:
function myFunction(data) {
var timeStamp = data[i][timeStampappr];
// If there is no timestamp, then do nothing.
if(timestamp){
var formattedDate = Utilities.formatDate(timestamp, "GMT", "MMM-dd-yyyy");
Logger.log(formattedDate);
}
}

How can I format a date string coming from the backend?

I am using Reactjs and ES6 in the frontend. And GraphQL to make some API calls.
I am getting a key named createDate with a value like this:
2017-03-29T07:19:05-07:00
And I need to format it like this:
03/29/2017 07:19 AM it should show AM or PM.
As this is an string and I am not using any library, I expect someone could guide me to a solution...
You can convert the String to a date object first
var d = new Date("2015-03-25T12:00:00-06:30");
Then define a function constructs the string you want to use for representing the date. For example
function dateToString(d) {
var year = d.getFullYear();
var month = d.getMonth() + 1; // getMonth() returns 0-11
.
.
.
return year + "-" + month "-" + ...;
}

Date.UTC() gets value null

From Server I get Date in UTC format like ,
2016-04-13T02:37:13.211316121-04:00
When I use this to display using new Date(data.Created_at) I get 7 min time difference. Like as I am displaying my date in format {{my_date | date: 'h:mm a'}}, insted showing 12:05 PM, it dispalys 11:58 AM. So I tried this,
data.Created_at = new Date(Date.UTC(data.Created_at))
which returns null value. Is there any problem in my code? How should I get perfect date?
If you check syntax of Date.UTC,
Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]])
It expects value in different variables and not in date string. You can split it and manually parse it.
You can try something like this:
JSFiddle
var d = "2016-04-13T02:37:13.211316121-04:00";
var date_arr = d.split(/[-|T|\.|:]/);
var o = new Date(Date.UTC(date_arr[0], date_arr[1], date_arr[2], date_arr[3], date_arr[4], date_arr[5]));
console.log(date_arr, o);
Also, it gives me 8:07 AM, considering the time is 2:37 and my timezone is +5:30.
Use it like this
Date.UTC(year,month,day,hours,minutes,seconds,millisec)
The code you are using is invalid way to handle date. You can use this code
new Date('2016-04-13T02:37:13.211316121-04:00').toISOString();
var created_at = new Date(createdAt);
var created_at_date = (created_at.getUTCMonth()+1) + "/" + created_at.getUTCDate() + "/" + created_at.getUTCFullYear() + "/" + created_at.getHours() + ":"
+ created_at.getMinutes() + ":" + created_at.getSeconds();
Hope this will work for you!!!

Converting string to date object, adding two hours and converting back to string (JavaScript)

I have a date string, want to convert it into a date object, add 2 hours and print out the converted date object back to a variable. But I get the error listed bellow:
// dateTime: 2013-09-27 09:50:05
var dateTime = $("#inputDatetime").val();
var startDate = dateTime;
var date = new Date(startDate);
var duration = 2;
var endDate = date;
endDate.setHours(date.getHours()+duration)
var dateString = endDate.format("dd-m-yy hh:mm:ss");
Error:
Uncaught TypeError: Object [object Date] has no method 'format'
Why do I get this TypeError?
Vaibs,
there is no method "format", you can do formating using available methods from Date Object.
please don't use plugin
example :
// dd-mm-yy hh:mm:ss
function formatDate(date) {
return ((date.getDate()<10?'0':'')+date.getDate()) + "-"+
(((date.getMonth()+1)<10?'0':'') + (date.getMonth()+1)) + "-" +
date.getFullYear() + " " +((date.getHours()<10?'0':'')+date.getHours()) + ":" +
(date.getMinutes()<10?'0':'') + date.getMinutes() + ":" +
(date.getSeconds()<10?'0':'') + date.getSeconds();
}
*thank you #donot
Use jquery ui date parser.
http://docs.jquery.com/UI/Datepicker/parseDate
This is the best function for parsing dates out of strings that I've had the pleasure to work with in js. And as you added the tag jquery it's probably the best solution for you.
.format() is not a valid Date method. JavaScript does not have an easy way to format dates and times with a user-specified format. The best you can do (without separate plugins) is to create your own string by getting each component of the date separately, and formatting/concatenating them.
I've used this before and it seems to work!
var dateString = endDate.toString("dd-m-yy hh:mm:ss");

Categories

Resources