Javascript Date formatting issue [duplicate] - javascript

This question already has answers here:
Format JavaScript date as yyyy-mm-dd
(50 answers)
Closed 6 months ago.
I want to obtain a date in yyyy-mm-dd format from a JavaScript Date object.
new Date('Aug 5 2022').toISOString().split('T')[0]
From above line, I'm expecting 2022-08-05 but getting 2022-08-04
how to solve it?

This issue occurs because you try to convert to toISOString it automatically convert to UTC, I am confident you are not in UTC area. So to fix this use:
new Date('Aug 5 2022 GMT+00').toISOString().split('T')[0]
So, convert it to UTC then to toISOString()

Your date gets converted to UTC. One way to fix this would be by adding UTC to your argument string.
new Date('Aug 5 2022 UTC').toISOString().split('T')[0]
Date.prototype.toISOString()
The toISOString() method returns a string
in simplified extended ISO format (ISO 8601), which is always 24 or 27
characters long (YYYY-MM-DDTHH:mm:ss.sssZ or
±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always
zero UTC offset, as denoted by the suffix Z. - Date.prototype.toISOString()

Below are two ways to get the yyyy-mm-dd string format that you asked about from a native JavaScript Date object:
Offsetting the date information according to the system time UTC offset:
const date = new Date();
const utcOffsetMs = date.getTimezoneOffset() * 60 * 1e3 * -1;
const offsetDate = new Date(date.getTime() + utcOffsetMs);
const dateStr = offsetDate.toISOString().slice(0, 10);
console.log(dateStr);
Get the individual date parts and format them with a leading 0 if necessary:
function getDateString (date) {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const dayOfMonth = date.getDate();
return `${year}-${String(month).padStart(2, '0')}-${String(dayOfMonth).padStart(2, '0')}`;
}
const date = new Date();
const dateStr = getDateString(date);
console.log(dateStr);

Related

Local date string in format yyyy/mm/dd is replacing mm with dd in javascript

So i have this string im my json:
"2019-05-24T14:43:39.89"
And this is my function for displaying this date
function getDateAndTime(dateString){
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
let date = new Date(dateString);
return addZero(date.getDay())+'/'+addZero(date.getMonth())+'/'+addZero(date.getFullYear())+ ' ' +addZero(date.getHours())+':'+addZero(date.getMinutes());
}
The problme is that the output is
05/04/2019 14:43
Its replacing month and days in new Date method and converts 24 to 4 i dont know why.
Is it any way to convert utc date string in format yyyy/mm/dd to dd/mm/yyyy date object? In javascript?
The getDay method returns the day of the week, not the day of the month. May 24 was a Friday, so getDay returns 5. You should use getDate, which returns 24.
Months are zero indexed, getMonth for May returns 4 not 5. So addZero(date.getMonth()) should be addZero(date.getMonth() + 1).

Material2 Datepicker - Convert date to timestamp without time [duplicate]

Can I convert iso date to milliseconds?
for example I want to convert this iso
2012-02-10T13:19:11+0000
to milliseconds.
Because I want to compare current date from the created date. And created date is an iso date.
Try this
var date = new Date("11/21/1987 16:00:00"); // some mock date
var milliseconds = date.getTime();
// This will return you the number of milliseconds
// elapsed from January 1, 1970
// if your date is less than that date, the value will be negative
console.log(milliseconds);
EDIT
You've provided an ISO date. It is also accepted by the constructor of the Date object
var myDate = new Date("2012-02-10T13:19:11+0000");
var result = myDate.getTime();
console.log(result);
Edit
The best I've found is to get rid of the offset manually.
var myDate = new Date("2012-02-10T13:19:11+0000");
var offset = myDate.getTimezoneOffset() * 60 * 1000;
var withOffset = myDate.getTime();
var withoutOffset = withOffset - offset;
console.log(withOffset);
console.log(withoutOffset);
Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.
EDIT
Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.
A shorthand of the previous solutions is
var myDate = +new Date("2012-02-10T13:19:11+0000");
It does an on the fly type conversion and directly outputs date in millisecond format.
Another way is also using parse method of Date util which only outputs EPOCH time in milliseconds.
var myDate = Date.parse("2012-02-10T13:19:11+0000");
Another option as of 2017 is to use Date.parse(). MDN's documentation points out, however, that it is unreliable prior to ES5.
var date = new Date(); // today's date and time in ISO format
var myDate = Date.parse(date);
See the fiddle for more details.
Yes, you can do this in a single line
let ms = Date.parse('2019-05-15 07:11:10.673Z');
console.log(ms);//1557904270673
Another possible solution is to compare current date with January 1, 1970, you can get January 1, 1970 by new Date(0);
var date = new Date();
var myDate= date - new Date(0);
Another solution could be to use Number object parser like this:
let result = Number(new Date("2012-02-10T13:19:11+0000"));
let resultWithGetTime = (new Date("2012-02-10T13:19:11+0000")).getTime();
console.log(result);
console.log(resultWithGetTime);
This converts to milliseconds just like getTime() on Date object
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
var date = new Date(date_string);
var milliseconds = date.getTime();
This worked for me!
if wants to convert UTC date to milliseconds
syntax : Date.UTC(year, month, ?day, ?hours, ?min, ?sec, ?milisec);
e.g :
date_in_mili = Date.UTC(2020, 07, 03, 03, 40, 40, 40);
console.log('miliseconds', date_in_mili);
In case if anyone wants to grab only the Time from a ISO Date, following will be helpful. I was searching for that and I couldn't find a question for it. So in case some one sees will be helpful.
let isoDate = '2020-09-28T15:27:15+05:30';
let result = isoDate.match(/\d\d:\d\d/);
console.log(result[0]);
The output will be the only the time from isoDate which is,
15:27

Wrong difference when calculating the difference between the present day and another date

I need your help.
My code is not returning the proper differential value when calculating the difference between the present date minus another date (UK Date Standard)
Ex.
The correct answers should result to:
30/01/2015 - 30/01/2015 = 0
30/01/2015 - 29/01/2015 = 1
30/01/2015 - 31/01/2015 = -1
Current code:
var x = "30/01/2015"
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var today = new Date();
var secondDate = new Date(x);
var diffDays = Math.ceil((secondDate.getTime() - today.getTime())/(oneDay));
alert(diffDays)
new Date("30/01/2015").toSTring() will return "Thu Jun 01 2017 00:00:00 GMT+0200 (CEST)".
The date string format you pass must wether be http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 or https://www.rfc-editor.org/rfc/rfc2822#page-14
You can also put it this way new Date(2015,0,30);
More informations here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Your date string variable x is in wrong format.
From constructor's parameters part of Date object description
dateString
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
Use
var x = '2015-01-30'
JSFiddle for your case.

Parsing Date with javascript in FireFox

I have strange date format like this dMMMyyyy (for example 2Dec2013).
I'm trying to create Date object in my javascript code:
var value = "2Apr2014";
var date = new Date(value);
alert(date.getTime());
example
in Google Chrome this code works fine but in FireFox it returns Null
Can anyone suggest something to solve this problem
Thanks.
How about just parsing it into the values new Date accepts, that way it works everywhere
var value = "02Apr2014";
var m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var month = value.replace(/\d/g,''),
parts = value.split(month),
day = parseInt(parts.shift(), 10),
year = parseInt(parts.pop(), 10);
var date = new Date(year, m.indexOf(month), day);
FIDDLE
This fiddle works in both firefox and chrome
var value = "02 Apr 2014";
var date = new Date(value);
alert(date.getTime())
Check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
I would suggest using something like jQuery datepicker to parse your dates.
I haven't tested it but it seems you'd need something like:
var currentDate = $.datepicker.parseDate( "dMyy", "2Apr2014" );
jsFiddle
Just be aware of:
d - day of month (no leading zero)
dd - day of month (two digit)
M - month name short
y - year (two digit)
yy - year (four digit)
However if for some reason you really wanted to do it yourself, then you could check out this link: http://jibbering.com/faq/#parseDate
It has some interesting examples on parsing dates.
Whilst not exactly what you want, the Extended ISO 8601 local Date format YYYY-MM-DD example could be a good indication of where to start:
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* #param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* #return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
You can use following JavaScript Library for uniform date parser across browser.
It has documentation
JSFIDDLE
code:
var value = "2Apr2014";
var date =new Date(dateFormat(value));
alert(date.getTime());

What is wrong with this javascript date difference calculate function?

Any idea why this function doesn't work properly in Internet Explorer?
function days_between(check_in, check_out)
{
var oneDay = 24*60*60*1000;
var firstDate = new Date(check_in);
var secondDate = new Date(check_out);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
return diffDays;
}
in internet explorer it shows NaN as result.
im calling this function in this date format
var check_in = "2012-02-09";
var check_out = "2012-02-12";
var range = days_between(check_in, check_out);
Regards
IE doesn't support Date.parse or passing "2012-02-09" (with ISO dates) to new Date, you need to parse it yourself and pass new Date( 2012, 1, 9 ) or use a Date.parse shim for ISO dates
The date format you're passing (yyyy-mm-dd) isn't supported by Date. See the note here that says it must be in a format parsable by parse. See here for acceptable parse formats: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse
You have problem in creating the Date Object
Date objects are created with the Date() constructor.
There are four ways of instantiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of instantiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)
(Taken from http://www.w3schools.com/js/js_obj_date.asp)
You are giving the date arguments in an incorrect format. You can expect javascript to support these formats:
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
To fix your immediate problem, you can use replace() to format your arguments.
function days_between(check_in, check_out)
{
var firstDate = new Date(check_in.replace('-' , '/'));
var secondDate = new Date(check_out.replace('-' , '/'));
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / 86400000);
return diffDays;
}
And by the way, you can replace oneDay with a constant.

Categories