How to convert date to milliseconds by javascript? [duplicate] - javascript

This question already has answers here:
How do I get a timestamp in JavaScript?
(43 answers)
Closed 4 years ago.
I have multiple date's for example(25-12-2017) i need them to be converted to milliseconds by javascript

One way is to use year, month and day as parameters on new Date
new Date(year, month [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
You can prepare your date string by using a function.
Note: Month is 0-11, that is why m-1
Here is a snippet:
function prepareDate(d) {
[d, m, y] = d.split("-"); //Split the string
return [y, m - 1, d]; //Return as an array with y,m,d sequence
}
let str = "25-12-2017";
let d = new Date(...prepareDate(str));
console.log(d.getTime());
Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

var dateTokens = "2018-03-13".split("-");
//creating date object from specified year, month, and day
var date1 = new Date(dateTokens[0], dateTokens[1] - 1, dateTokens[2]);
//creating date object from specified date string
var date2 = new Date("2018-03-13");
console.log("Date1 in milliseconds: ", date1.getTime());
console.log("Date2 in milliseconds: ", date1.getTime());
console.log("Date1: ", date1.toString());
console.log("Date2: ", date2.toString());

In addition to using vanilla javascript, you can also use many libraries to get more functions.
like date-fns, moment.js etc
For example, use moment.js you can convert date to milliseconds by moment('25-12-2017', 'DD-MM-YYYY').valueOf(), more elegant and powerful than vanilla javascript.

Related

Create Date object passing a date format of mmddyyyy [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 10 months ago.
I'm trying to create a date with the format 'mmddyyyy'. I've noticed I can pass a four digit string, but when I use the format above, it says invalid date. How can I go about this with pure js?
let dateString = '01012022'
let d = new Date(dateString)
maybe you want something like that
let dateString = '01012022'
let [match, dd, mm, yyyy] = dateString.match(/(\d{2})(\d{2})(\d{4})/)
// iso format
let d = new Date(`${yyyy}${mm}${dd}`)
Seems like you have to split your string into pieces then use common Date() constructor with separated day, month and year
//Your string with date
let dateString = '01012022';
//extracting 2 first numbers as m (month), 2 second as d (day) and the last 4 as y (year)
let {d,m,y} = /(?<m>\d{2})(?<d>\d{2})(?<y>\d{4})/.exec(dateString).groups;
//then create new date using constructor
let date = new Date(y,m,d);

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,

new Date() always read dd/mm/yyyy as mm/dd/yyyy(month first) hence day and month values get mixed resulting in NaN/Error [duplicate]

This question already has answers here:
How to convert dd/mm/yyyy string into JavaScript Date object? [duplicate]
(10 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
When converting date for example:
var dateObj = new Date("10/01/2019");
console.log(dateObj);
returns Tue Oct 01 2019 00:00:00 i.e. it takes in the day as month and likewise with the month value
How to make new Date() to take dd/mm/yyyy ??
Answer is here: https://stackoverflow.com/a/33299764/6664779
(From original answer) We can use split function and then join up the parts to create a new date object:
var dateString = "23/10/2019"; // Oct 23
var dateParts = dateString.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
document.body.innerHTML = dateObject.toString();

Javascript convert date string to object [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I'm trying to convert a date in string format to a Date object in JavaScript. The date is coming from the openweathermap.org API, which gives the date string in the following format:
'2018-04-28 09:00:00' or 'yyyy-mm-dd hh:mm:ss'
I know that the JavaScript Date class can take other string formats of dates, but this one returns NaN when I try anything with it. How can I convert a date string, like the one above, and convert it easily to a JavaScript object? Thanks!
Since you are getting NaN while directly converting the string to date. You can split the string on spaces, - and : and then pass the value to date constructor and generate the date object.
const str = `2018-04-28 09:00:00`;
const [date, time] = str.split(' ');
const [year, month, day] = date.split('-');
const [hh, mm, sec] = time.split(':');
const dateObj = new Date(year, month - 1, day, hh, mm, sec);
console.log(dateObj);
As pointed out by #RobG, this could also be done using the regex.
const str = `2018-04-28 09:00:00`;
var b = str.split(/\D/);
var date = new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
console.log(date);
const str = `2018-04-28 09:00:00`,
date = new Date(...(str.split(/\D/).map((v,i)=>i==1?--v:v)));
console.log(date);
Just try new Date(str)
d = new Date("2018-04-20 09:00:00")
Fri Apr 20 2018 09:00:00 GMT+0800 (Hong Kong Standard Time)
d.getDate()
20
ref: https://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format

Convert specific date in Javascript [duplicate]

This question already has answers here:
Parse DateTime string in JavaScript
(9 answers)
Closed 5 years ago.
I have problem with convert date which I get from API. Format is for example "16/09/25"
I try do it like this
var x = new Date(dateFromApi)
and console thorw me error.
Parsing a date string is very simple. A function that will work in any host from IE 4 onward is:
function parseDMY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[1]-1, b[0]);
}
console.log(parseDMY('16/09/25'));
Where the year is >= 0 or <= 99, 1900 is added so 25 becomes 1925. Preserving years in this range (so 25 is 0025) requires an additional line of code.
It is safest to provide the Date constructor with the individual parts of the date (i.e., year, month and day of the month).
In ES6 you can provide those elements like this:
var x = new Date(...dateFromApi.split('/').reverse().map( (p,i) => p-(i%2) ));
The map is needed to subtract one from the month number, as it should be zero-based in numeric format.
Note the new Date(year, month, day) version of the constructor will assume 19xx when you provide only 2 digits.
var dateFromApi = "16/09/25"
var x = new Date(...dateFromApi.split('/').reverse().map( (p,i) => p-(i%2) ));
console.log(x.toDateString());
In ES5, it would be a bit longer, like this:
new (Date.bind.apply(Date, (dateFromApi+'/').split('/').reverse()
.map(function (p,i) { return p-(i==2); })));
var dateFromApi = "16/09/25"
var x = new (Date.bind.apply(Date, (dateFromApi+'/').split('/').reverse()
.map(function (p,i) { return p-(i==2); })));
console.log(x.toDateString());
Of course, this assumes that the input format is consistently in the order DD/MM/YY (or D/MM/YYYY, as long as the order is the same); that valid dates are passed, and that you accept how 2-digit years are mapped to 4-digit years.
Your format is DD/MM/YY and it is not accepted by Date and will throw an error.
This is because, as mentioned by #MattJohnson, the accepted Date formats vary by locale and the only official format is YYYY-MM-DD (which is derived from ISO date string. Read here).
In most cases, Date will accept the format YY-MM-DD. So we can simply do this:
var date = "16/09/25"; // date received from API
var split_date = date.split('/'); // outputs ["16","09",""25"]
var rearranged_date = [split_date[1], split_date[0], split_date[2]].join('/'); // outputs "09/16/25"
var proper_date = new Date(rearranged_date);
In other cases, it is best to provide the full-year YYYY instead of just YY.

Categories

Resources