Date.UTC() gets value null - javascript

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!!!

Related

Extract date and time from datetime string in javascript

My datetime string is of below format:
var sdt = '2022-05-19T13:00:00';
I want to extract the date and time separately and below is my code:
((sdt.getMonth() > 8) ? (sdt.getMonth() + 1) : ('0' + (sdt.getMonth() + 1))) + '/' + ((sdt.getDate() > 9) ? sdt.getDate() : ('0' + sdt.getDate())) + '/' + sdt.getFullYear() + ' ' + (sdt.getHours()) + ':' + (sdt.getMinutes()) + ':00'
From the above code, date is getting extracted correctly but not the time. any help pls?
You can use the Date object and use Date#toLocaleDateString & Date#toLocaleTimeString method to get your time and date
Or even the Date#toLocaleString to get both at the same time !
const sdt = '2022-05-19T13:00:00';
const date = new Date(sdt)
console.log(date.toLocaleString())
console.log(date.toLocaleDateString())
console.log(date.toLocaleTimeString())
Note that you can specify the location to get the date for a current country
date.toLocaleString('en-GB')
I always use a moment.js when dealing with date and time .
Just pass the datetime string and specify the format of the output you want .
import moment from 'moment'
var sdt = '2022-05-19T13:00:00';
let time = moment(sdt).format("HH:mm:ss")
let date = moment(sdt).format("DD/MM/YYYY")
console.log(time) //01:00:00
console.log(date) //19/05/2022
https://momentjs.com/ checkout this page to learn about more formats
use the Date() constructor:
const sdtString = '2022-05-19T13:00:00'; // https://en.wikipedia.org/wiki/ISO_8601
const sdt = new Date(sdtString); // Date Object {}
then to get the respective date / time use:
Date.prototype.toLocaleTimeString()
Date.prototype.toLocaleDateString()
Also, worth remembering that getMonth() gives the month's index (zero based), not the number.

How do I convert UTC DateTime to local DateTime without ending up with a different format

I have specific DateTime values in this format 'YYYY-MM-DDThh:mm:ss.ms' (e.g. '2022-05-10T13:44:00.0000000') and I need to convert them to local DateTime (which is UTC+2 for me) without changing the format (so '2022-05-10T15:44:00.0000000' is the desired result (even better would be without the milliseconds but that would just be the icing on the cake)).
I've searched far and wide but every alleged solution I find either changes the format or doesn't change the time at all.
This is what I have right now, it successfully converts the time to local time but by running it through .toISOString() to get the original format back it converts it back to UTC time.
//Input: event.start.dateTime = '2022-05-10T13:44:00.0000000'
let startDateTime = new Date(event.start.dateTime);
startDateTime.setMinutes(startDateTime.getMinutes() -
startDateTime.getTimezoneOffset());
document.getElementById('ev-start').value =
startDateTime.toISOString().slice(0,16);
//Output: '2022-05-10T13:44:00.000Z'
I couldn't find a clean and satisfying solution so I decided to just to the formatting myself. Here's what I ended up with:
Input: '2022-05-10T13:44:00.0000000'
let startDateTime = new Date(event.start.dateTime);
startDateTime.setMinutes(startDateTime.getMinutes() -
startDateTime.getTimezoneOffset());
let localStartDateTime = startDateTime.getFullYear() + "-" +
(startDateTime.getMonth() + 1).toString().padStart(2, '0') +
"-" + startDateTime.getDate().toString().padStart(2, '0') +
"T" + startDateTime.getHours().toString().padStart(2, '0') +
":" + startDateTime.getMinutes().toString().padStart(2, '0')
+ ":" +
startDateTime.getSeconds().toString().padStart(2, '0');
document.getElementById('ev-start').value =
localStartDateTime;
Output: '2022-05-10T15:44:00'
Hope this helps
const startDateTime = new Date('2022-05-10T13:44:00.0000000');
const outputDateTime = new Date(startDateTime.toString()).toISOString().slice(0, 19);
//document.getElementById('ev-start').value = outputDateTime
console.log(outputDateTime);

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

Javascript date to sql date object

I'm trying to write a query that takes a Javascript date object and then puts it in an object type that is recognized by both SQL Server and Oracle database types.
The issue is that I'm using webservices. So it has to be a string, not an actual passed parameter. Here's what I mean:
var date = new Date();
var firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDayOfMonth = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var webServicesQueryWhereClause = 'readDate BETWEEN '+firstDayOfMonth+' AND '+lastDayOfMonth;
Except firstDayOfMonth and lastDayOfMonth are surrounded by something like to_date() to actually put them in a date format that the databases can read. For example:
var webServicesQueryWhereClause = 'readDate BETWEEN to_date('+firstDayOfMonth+') AND to_date('+lastDayOfMonth+') ';
What should I use to put those dates in a form that can be read by both SQL Server and Oracle?
Have you tried the solutions presented here:
Convert JS date time to MySQL datetime
The title should be called
"Convert JS date to SQL DateTime"
I happened to need to do the same thing as you just now and I ran across this after your question.
This is from the other post by Gajus Kuizinas for those who want the answers on this page:
var pad = function(num) { return ('00'+num).slice(-2) };
var date;
date = new Date();
date = date.getUTCFullYear() + '-' +
pad(date.getUTCMonth() + 1) + '-' +
pad(date.getUTCDate()) + ' ' +
pad(date.getUTCHours()) + ':' +
pad(date.getUTCMinutes()) + ':' +
pad(date.getUTCSeconds());
or
new Date().toISOString().slice(0, 19).replace('T', ' ');
The first one worked for me. I had a reference problem with the toISOString as well although I would prefer the one liner. Can anyone clarify how to use it and know the limitations on where one can reference it?
Good luck!
using MomentJs it will be pretty easy.
moment().format('YYYY-MM-DD HH:mm:ss')
https://momentjs.com/
In my case I was trying to get a TIMESTAMP and store it to a variable so I can pass that array inside a SQL query(Row insertion)
The following worked for me quite well.
var created_at = new Date().toISOString().slice(0, 19).replace('T', ' ');
Maybe I found a bit shorter approach - tested on MSSQL and Postgres
const date = (new Date()).toLocaleString("en-US")
Enjoy!
I use:
const datetimeSQL = new Date().toISOString().split('T').join(' ').split('Z').join('');
// return '2022-09-02 19:54:17.028'

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