This question already has answers here:
new Date('dd/mm/yyyy') instead of newDate('mm/dd/yyyy') [duplicate]
(3 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
I have an API which gives the date format like 01/04/2020 00:17:26 and we are using the JavaScript code below:
function getLocalTime(timestamp){
try {
let localTime = new Date(timestamp.replace('at ','') + ' GMT+530');
return localTime;
} catch(e){
return timestamp;
}
}
vat date = getLocalTime('01/04/2020 00:17:26');
console.log(date);
The above code is returning Sat Jan 04 2020 00:17:26 GMT+0530 (India Standard Time) But expected result will be as like Wed Apr 01 2020 00:17:26 GMT+0530 (India Standard Time)
Please help us with this.
The issue is the wrong date format you are using.
Your format: DD/MM/YYYY
Expected format: MM/DD/YYYY
Still, if the input format you are expecting (from the user) is DD/MM/YYYY (e.g. 01/04/2020 00:17:26), then you can use regex to extract the date info like so
function getLocalTime(timestamp){
try {
const datePart = timestamp.match(/^(\d{2})\/(\d{2})\/(\d{4})/);
const day = datePart[1];
// month goes from 0 to 11
const month = datePart[2] - 1;
const year = datePart[3];
const localTime = new Date(timestamp.replace('at ','') + ' GMT+0530');
localTime.setFullYear(year);
localTime.setMonth(month);
localTime.setDate(day);
return localTime;
} catch(e){
return timestamp;
}
}
const date = getLocalTime('01/04/2020 00:17:26');
console.log(date);
Update
#RobG proposed a fantastic solution (see in comments below).
function getLocalTime(timestamp) {
try {
const matches = timestamp.split(/\D+/); // or use timestamp.match(/\d+/g)
return new Date(Date.UTC(matches[2], matches[1]-1, matches[0], matches[3]-5, matches[4]-30, matches[5]));
} catch(e){
return timestamp;
}
}
const date = getLocalTime('01/04/2020 00:17:26');
console.log(date);
Related
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
new Date('2020-08-18 07:52') is working in Chrome, it returned
Tue Aug 18 2020 07:52:00 GMT+0800 (Malaysia Time)
but safari gave me invalid date? what's the best way to fix this? this bug in safari is breaking my entire app.
without need for tools/plugins/packages, I would simply separate the received date:
var apiDate = '2020-08-18 07:52'
var [ date, time ] = apiDate.split(' ')
var [ year, month, day ] = date.split('-')
var [ hour, minute ] = time.split(':')
var newDate = new Date(year, month - 1, day, hour, minute, 0)
// Tue Aug 18 2020 07:52:00
I would just be careful about TimeZones, as your date has no time zone description ...
Note
from the code above, one might think that subtracting 1 from a string is invalid, but that's the caveats of javascript...
"08" + 1 = "081"
"08" - 1 = 7
if the format is always the same, you can also do:
var apiDate = '2020-08-18 07:52'
var newDate = new Date(`${apiDate.replace(' ', 'T')}:00`) // '2020-08-18T07:52:00'
// Tue Aug 18 2020 07:52:00
This question already has answers here:
Compare two dates with JavaScript
(43 answers)
Closed 2 years ago.
I have Datetimes formated as "16 Apr 2020 02:07 PM CST" and I need to compare it to another datetime just like that to know which date came first.
What I tried to do until now was:
var firstDate = "16 Apr 2020 02:07 PM CST";
var secondDate = "23 Apr 2020 06:07 AM CST";
var diff = Math.abs(firstDate - secondDate);
That or I tried to check if one was greater than the other and got similar results.
You should check time in milliseconds (timestamp) to compare dates:
var firstDate = new Date("16 Apr 2020 02:07 PM CST");
var secondDate = new Date("23 Apr 2020 06:07 AM CST");
if (firstDate.getTime() < secondDate.getTime()) {
console.log('First Date came first');
} else {
console.log('Second Date came first');
}
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
Need to format this date:
[Wed Jul 03 2019 00:00:00 GMT+0200 (Central European Summer Time),
Thu Aug 01 2019 23:59:59 GMT+0200 (Central European Summer Time)]
Into simple mm/dd/yyyy, but not with moment. Cus moment is to heavy.
This is my format function which get array date = [startDate, endDate]
formatDate = (date) => {
const newDate = new Date(date);
const dateFormatted = [];
for (let i = 0; i < date.length; i++) {
dateFormatted[i] = `${newDate.getMonth() + 1}/${newDate.getDate()}/${newDate.getFullYear()}`;
}
return dateFormatted;
};
As result I am getting this NaN/NaN/NaN
Any suggestion, advice?
I recommend you to not customize your Date variables it in that way,
You should define your LOCALE_ID which means that you don't need to use custom format for your Date (or currency, time etc.) variables. For example,
import { LOCALE_ID } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule, {
providers: [{provide: LOCALE_ID, useValue: 'en-US' }]
});
Source: https://angular.io/api/core/LOCALE_ID#description
So, the result you want is something like:
`${d.getMonth().toString().padStart(2,'0')}/${d.getDate().toString().padStart(2,'0')}/${d.getFullYear()}`
So your function should be:
let formatDate = (date) => {
let d = new Date(date)
return `${d.getMonth().toString().padStart(2,'0')}/${d.getDate().toString().padStart(2,'0')}/${d.getFullYear()}`;
}
and then you can call it on a list of dates.
let dateList = [new Date(), new Date()]
formattedDates = dateList.map(formatDate)
You can also extend this to take a list of dates to process.
let formatDates = (dates) => dates.map(formatDate);
so you can also pass in a list of dates to process, leveraging the singular formatDate
Simple js function to convert Date object to string:
const date = new Date();
function tommddyyyy(date) {
return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
}
console.log(tommddyyyy(date));
The posted code doesn't produce NaN/NaN/NaN, it formats the date as m/d/y.
Your problem is here:
for (let i = 0; i < date.length; i++)
The value of date is a string like "Wed Jul 03 2019 00:00:00 GMT+0200" with length 33, so you get 33 formatted dates. There are already many questions on parsing and formatting dates, so I'll mark this as a duplicate of those.
angular has it's own formatDate function, I'd recommend using it:
import {formatDate} from '#angular/core';
formatDate(date, 'short', 'en-US');
1st arg is date or string, second is format (or shorthand format as used here), 3rd is the locale.
I expect date_arr to be an array of strings parsable as dates. Then I would use this plain javascript solution:
formatDate = (date_arr) => {
return date_arr.map( dt => {
// create an date object and convert to an iso-string (yyyy-mm-dd)
var iso = new Date(dt).toISOString().substr(0,10);
// rearrange the values as needed (mm-dd-yyyy)
iso = `${iso.substr(5)}-${iso.substr(0,4)}`;
// replace delimiter '-' with '/'
return iso.replace(/-/g, '/');}
);
};
// sample call
formatDate(['2019-05-03', new Date()]);
// ["05/03/2019", "07/18/2019"]
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I hardcoded date string in one variable and passing this in new Date()
let hardcoded = "10/4/2018 12:00:00 AM";
console.log($.type(hardcoded)); // String is printing
console.log(hardcoded); // 10/4/2018 12:00:00 AM is printing
var d = new Date(hardcoded);
console.log(d); // Thu Oct 04 2018 00:00:00 GMT+0530 (India Standard Time) is printing
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here in variable 'd' i am getting proper date .. no any issue.
But in below case same string i am getting in convertedDate variable what i hardcode above but its not working ..
let convertedDate = new Date().toLocaleString("en-us", {
timeZone: 'UTC'
});
console.log($.type(convertedDate)); // String is printing
console.log(convertedDate); // 6/26/2019 12:02:50 PM is printing
var d = new Date(convertedDate);
console.log(d)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
but here in variable d :- "Invalid date" is coming..
Try this
var d = new Date(convertedDate.toDateString())
Your passing
6/26/2019, 12:30:57 PM
but Date() is expecting
2019-06-26T11:30:57.000Z
.toDateString() will convert
6/26/2019, 12:30:57 PM
to
2019-06-26T11:30:57.000Z
As you are having this problem in IE11, I found this which may cast light on the issue
IE's toLocaleString has strange characters in results
When using the JavaScript Date instance to create new date, the date string given to the date constructor should be an RFC2822 or ISO 8601 formatted date, not local.
So, I suggest you could modify your code as below:
let convertedDate = new Date();
var convertedDatestring = convertedDate.toLocaleString("en-us", {
timeZone: 'UTC'
});
console.log($.type(convertedDatestring)); // String is printing
console.log(convertedDatestring); // 6/26/2019 3:24:04 PM
var d = new Date(convertedDate.toUTCString());
console.log(d); //Wed Jun 26 2019 23:24:04 GMT+0800
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 4 years ago.
I am trying to get a string with date/time on this format: "YYYY-MM-DD-HH-MM"
I cannot find a proper way to do it?
This is what I have at the moment:
var x = new Date();
var TimeStamp = x.toString();
Outputs:
Tue Oct 30 2018 14:33:03 GMT+0000 (UTC)
Use Date methods and format it.
var date = new Date();
var output = date.getFullYear()+'-'+("0" + (date.getMonth() + 1)).slice(-2)+'-'+("0" + date.getDate()).slice(-2)+'-'+date.getHours()+'-'+date.getMinutes()
console.log(output)
Or you can use momentjs format.
console.log(moment().format('YYYY-MM-DD-HH-mm'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>