date to timestamp in javascript - javascript

Is it possible in javascript to convert some date in timestamp ?
i have date in this format 2010-03-09 12:21:00 and i want to convert it into its equivalent time stamp with javascript.

In response to your edit:
You need to parse the date string to build a Date object, and then you can get the timestamp, for example:
function getTimestamp(str) {
var d = str.match(/\d+/g); // extract date parts
return +new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]); // build Date object
}
getTimestamp("2010-03-09 12:21:00"); // 1268158860000
In the above function I use a simple regular expression to extract the digits, then I build a new Date object using the Date constructor with that parts (Note: The Date object handles months as 0 based numbers, e.g. 0-Jan, 1-Feb, ..., 11-Dec).
Then I use the unary plus operator to get the timestamp.
Note also that the timestamp is expressed in milliseconds.

+(new Date())
Does the job.

The getTime() method of Date object instances returns the number of milliseconds since the epoch; that's a pretty good timestamp.

Related

Javascript Invalid Date String [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I am trying to extract date from a string 20170901000000. new Date(string) returns Invalid Date. The date string looks pretty straightforward to me but apparently javascript doesn't take it.
What formats does javascript new Date() method take? Is there a package taking more formats of date string?
Edit: The formats are from random users. The YYYYMMDDhhmmss is only one example. The package has to be able to determine what format it is by itself and parse it.
You have to parse your date string:
parseDateString = dateStr =>
dateStr.replace(
/^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})$/,
'$1-$2-$3 $4:$5:$6'
);
console.log(new Date(parseDateString('20170901000000')));
Hope this helps,
you can split that string and use this..
new Date (YYYY,MM,DD,HH,MM,SS)
/* from mdn */
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
Use a propper library like Moment.js:
const date = moment("20170901000000", "YYYYMMDDhhmmss");
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
When using a number passed to the date function it must be in the format of a unix timestamp.
new Date(value): A Unix Time Stamp which is an integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider that most Unix timestamp functions count in seconds).
Otherwise you need to generate a valid time string:
new Date(dateString): String value representing a date. The string should be in a format recognized by the Date.parse() method
Since your format is YYYYMMDDHHMMSS and not a unix timestamp we can use the latter dateString approach and use regex to create a valid string date:
let format = '20170901000000'
.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:$6')
console.log('format:', format)
console.log('date:', new Date(format))
Also see the [document for Javascript Date.parse][1]
Examples
new Date('2017-09-01 00:00:00');
new Date('Sept 01, 2017 00:00:00');
For more libraries you can use Moment.js or Day.js

Moment.js to get UTC time as date object instead of string

I want to get the UTC time using moment.utc() as a date object instead of epoch or string (moment.utc().format() or using .toISOString()). moment.utc().toDate() returns my local time. Any help would be appreciated.
You can use moment().toDate(). If you coerce the date to a string (e.g. by sending it to the console, alert, etc.), the built-in (implementation dependent) toString method will typically use the host timezone settings to generate a string, e.g.
var m = moment().toDate(); // Equivalent to new Date()
console.log(m + '') // coerce to string uses built-in toString
console.log(m.toISOString()) // ISO 8601 string offset +0000
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

How to check if 2017-03-29T06:45:00.000Z is equal to the date and time now?

I have a date with the format 2017-03-29T06:45:00.000Z, how do I check if it is equal or less to the date and time now?
If I check with
var currentTime = new Date();
if("2017-03-29T06:45:00.000Z" <= currentTime){
its not right since current date is in the format Wed Mar 29 2017 08:59:18 GMT+0200(CEST)
Any input appreciated, thanks
You are trying to compare a string to a Date Object. Because the two data types do not match, javascript tries to compare them by their value and calls currentTime.valueOf(). This evaluates to a integer like 1490781568805. Javascript then tries to compare the string to the evaluated integer. The result is different than you might expect, because the individual char codes of the string are compared to the integer.
"2017-03-29T06:45:00.000Z" <= new Date() // string compared to the Date object
"2017-03-29T06:45:00.000Z" <= new Date().valueOf() // javascript trying get a value for the date object
"2017-03-29T06:45:00.000Z" <= 1490781568805 // evaluates to false
You can just parse your date string to a Date object using Date.parse()
Date.parse("2017-03-29T06:45:00.000Z") <= new Date() // two Date objects are compared

Date ISO date string issue

console.log(new Date('2016-05-24').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/26/2016').toISOString()); // '2016-05-23T23:00:00.000Z' // why?
I am sending data to the server to parse and want to ensure that server will encode my date correctly.
What is the simplest way to convert date to string as '2016-05-24T00:00:00.000Z' in both cases?
Thanks
console.log(new Date('2016-05-24 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/24/2016 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
Append the timezone to the date before creating a new date object so that the string parsing code in the Date constructor doesn't get confused. Always disambiguate if possible.
Your code was using different timezones for each parse because of the way the dates were formatted. One was using +0 timezone, other was using -1 timezone hence the date being pulled back an hour when the ISO string was created.
One is parsing in UTC time, one is parsing in local time.
new Date('2016-05-24').toISOString() // '2016-05-24T00:00:00.000Z'
new Date('05/24/2016').toISOString() // '2016-05-24T07:00:00.000Z'
Playing around, here's one solution:
new Date(new Date('05/24/2016') - (new Date()).getTimezoneOffset() * 60000).toISOString() // '2016-05-24T00:00:00.000Z'
The strategy:
Create the new offset date
Subtract the offset
Create a new date from that result
Reference links:
javascript toISOString() ignores timezone offset
Why does Date.parse give incorrect results?
On further consideration, I'd recommend parsing the date string into something that is "universal" before passing it to the date constructor. Something like:
var tmp = ('05/24/2016').split('//');
var universal = [tmp[2], tmp[0], tmp[1]].join('-'); // 2016-05-24
...
Also, Moment.js does this sort of thing very neatly.
Use the getDate(), getMonth() and getFullYear() methods to strip out what you need.

Is there a built-in JavaScript function to process a time string?

To make a time like "2009-05-02 00:00:00" to "2009-05-02".
I know I can achieve this by a regular expression, but is there a built-in function that can do this?
There's no built-in date function that can do that. As a matter of fact if you create a new Date object in JavaScript with that date format, you get an Invalid Date Error.
You are correct in using a regular expression or string manipulation in this case.
Here's a list of all the JavaScript Date Functions.
To simply get the date portion of the string and display it without converting into a Date Object. You can simply do this:
var dateString = "2009-05-02 00:00:00"
alert(dateString.substring(0,10)); // Will show "2009-05-02"
To convert this string into a proper JavaScript Date Object, you can use this snippet:
function sqlTimeStampToDate(timestamp) {
// This function parses SQL datetime string and returns a JavaScript Date object
// The input has to be in this format: 2007-06-05 15:26:02
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
The format will be "ddd MMM dd YYYY hh:mm:ss" + TimeOffSet, but you will be able to use any of the standard JavaScript date functions.
See below for two simple methods to get a date format of "2009-05-02", from the initial format, that is "2009-05-02 00:00:00".
<script type="text/javascript">
var mydate, newdate1, newdate2;
mydate = "2009-05-02 00:00:00";
newdate1 = (mydate.split(/ /))[0];
alert('newdate 1: ' + newdate1);
newdate2 = mydate.substr(0,10);
alert('newdate 2: ' + newdate2);
</script>
You might find this helpful:
Return today's date and time
How to use the Date() method to get today's date.
getTime()
Use getTime() to calculate the years since 1970.
setFullYear()
How to use setFullYear() to set a specific date.
toUTCString()
How to use toUTCString() to convert today's date (according to UTC) to a string.
getDay()
Use getDay() and an array to write a weekday, and not just a number.
This is copy-paste from www.w3schools.com since I can't post a link to it...
Or just search Google for "JavaScript date function" or related. Regular expressions are used to match specific parts of strings, which is useful in searching, extraction and replacement, not really anything that would help you with formatting a date.

Categories

Resources