How to convert string into date in js [duplicate] - javascript

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 1 year ago.
I have string like
Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)
How I can convert it into date
2021-06-07

Convert it into Date object and than into string?
var date = new Date("Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)");
console.log(date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, 0) + "-" + String(date.getDay()).padStart(2, 0));

Date is represented as a standard with timestamp. You can't extract part if date and make its type as date. It would be string only. For formatting there are built in function like Intl. I am attaching here sample as well as link to Init documentation. You can explore more here Intl
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
timeZone: 'America/Los_Angeles'
};
var d= new Intl.DateTimeFormat('en-US', options).format(date);
console.log(d);

Try this,
var date = new Date("Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)");
const formatDate = date => [
date.getFullYear(),
(date.getMonth() + 1).toString().padStart(2, '0'),
date.getDate().toString().padStart(2, '0')
].join('-');
console.log(formatDate);
The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
join('-') : adding '-' symbol between every elements(for concatenation)
getMonth()+1 - Since the month starts with 0, 1 is added.

Create Date object from string and then use toISOString() method to convert it to required format YYYY-mm-dd.
const convertDate = (dateStr) => {
const myDate = new Date(dateStr)
return myDate.toISOString().split("T")[0];
}
console.log(convertDate("Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)"));

Related

How to convert date from react calendar in the dd/mm/yyyy format?

I am using react-calendar , Here I am getting a date in the following format
Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)
Now I am trying to convert it to dd/mm/yyyy. is there any way though which I can do this ?
Thanks.
The native Date object comes with seven formatting methods. Each of these seven methods give you a specific value -
toString() : Fri Jul 02 2021 14:03:54 GMT+0100 (British Summer Time)
toDateString(): Fri Jul 02 2021
toLocaleString() : 7/2/2021, 2:05:07 PM
toLocaleDateString() : 7/2/2021
toGMTString() : Fri, 02 Jul 2021 13:06:02 GMT
toUTCString() : Fri, 02 Jul 2021 13:06:28 GMT
toISOString() : 2021-07-02T13:06:53.422Z
var date = new Date();
// toString()
console.log(date.toString());
// toDateString()
console.log(date.toDateString());
// toLocalString()
console.log(date.toLocaleString());
// toLocalDateString()
console.log(date.toLocaleDateString());
// toGMTString()
console.log(date.toGMTString());
// toGMTString()
console.log(date.toUTCString());
// toGMTString()
console.log(date.toISOString());
Format Indian Standard time to Local time -
const IndianDate = 'Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)';
const localDate = new Date(IndianDate).toLocaleDateString();
console.log(localDate);
You could use the methods shown in this blogpost https://bobbyhadz.com/blog/javascript-format-date-dd-mm-yyyy from Borislav Hadzhiev.
You could a new date based on your calendar date and afterwards format it:
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
function formatDate(date) {
return [
padTo2Digits(date.getDate()),
padTo2Digits(date.getMonth() + 1),
date.getFullYear(),
].join('/');
}
console.log(formatDate(new Date('Wed Feb 02 2022 00:00:00 GMT+0530 (India Standard Time)')));
This is JavaScript default date format.
You can use libraries like momentjs, datefns, etc to get the result.
For example, if you are using momentjs:-
moment(date).format('dd/mm/yyyy);
Or if you don't want to use any third-party library you can get the result from JavaScript's default date object methods.
const date = new Date();
const day = date.getDate() < 10 ? 0${date.getDate()} : date.getDate();
const month = date.getMonth() + 1 < 10 ? 0${date.getMonth() + 1} : date.getDate() + 1;
const year = date.getFullYear();
const formattedDate = ${day}/${month}/${year};

javascript getTime() returns greater value for older date compared to new date

javascript getTime() returns the number of milliseconds form midnight Jan 1, 1970 and the time value in the Date Object. but,
new Date('Wed Sep 16 2105 05:30:00 GMT+0530').getTime()
// returns 4282502400000
new Date('Tue Oct 26 2015 05:30:00 GMT+0530').getTime()
// returns 1445817600000
Shouldn't the value retuned by the later (Tue Oct 26 2015 05:30:00 GMT+0530) be greater.
I want to find the list dates between a given date (inform of timestamp) and today. I wrote the code below with the assumption that the value returned by getTime() for older dates will always be lesser than newer dates.
var timestamp = new Date('9/15/2105, 12:00:00 AM').getTime();
var startDate = new Date(timestamp);
// Date.UTC() to avoid timezone and daylight saving
var date = new Date(Date.UTC(startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate()
));
var currentDay = new Date();
var currentDayTimestamp = new Date(Date.UTC(currentDay.getFullYear(),
currentDay.getMonth(),
currentDay.getDate()
)).getTime();
// day in millisec, 24*60*60*1000 = 86400000
date = new Date(date.getTime() + 86400000);
var dates = [];
console.info(date + ' : ' + date.getTime());
console.info(new Date(currentDayTimestamp) + ' : ' + currentDayTimestamp);
while(date.getTime() <= currentDayTimestamp) {
var dateObj = {
date: date.getUTCDate(),
month: date.getUTCMonth() + 1,
year: date.getUTCFullYear()
}
dates.push(dateObj);
date = new Date(date.getTime() + 86400000);
}
console.info(JSON.stringify(dates));
OUTPUT:
Wed Sep 16 2105 05:30:00 GMT+0530 (IST) : 4282502400000
Tue Oct 27 2015 05:30:00 GMT+0530 (IST) : 1445904000000
[]
The problem is a typo in your dates. One has the year 2105 which is much larger than 2015.

Javascript Date add days

var date = new Date();
var date2 = new Date();
daysinadvance = document.getElementById('AdvanceDays').value;
date2.setDate(date.getDate()+daysinadvance);
console.log(date2 + date + daysinadvance);
Fri Jan 28 2022 18:13:43 GMT+0000 (GMT Daylight Time)
Mon Apr 28 2014 18:13:43 GMT+0100 (GMT Standard Time)
60
If I pass in a directly typed number so + 60, it works fine but using the variable, I get a date in 2022. All I would like is the date2 to be current date + 60 days so I can update my validation.
Any help please?
Convert the value to a number first, e.g. with the unary plus operator:
var daysinadvance = +document.getElementById('AdvanceDays').value;
// ^ unary plus
Otherwise daysinadvance will be a string and you are doing string concatenation.

How can I convert this complicated date format to this in javascript

How can I convert this format "Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)" to just 2014-01-31 in Javascript ?? I know it should be simple but I didnt get it from google
var d = new Date("Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)");
var str = $.datepicker.formatDate('yy-mm-dd', d);
alert(str);
http://jsfiddle.net/3tNN8/
This requires jQuery UI.
jsFiddle Demo
Split the string based on the blank spaces. Take the parts and reconstruct it.
function convertDate(d){
var parts = d.split(" ");
var months = {Jan: "01",Feb: "02",Mar: "03",Apr: "04",May: "05",Jun: "06",Jul: "07",Aug: "08",Sep: "09",Oct: "10",Nov: "11",Dec: "12"};
return parts[3]+"-"+months[parts[1]]+"-"+parts[2];
}
var d = "Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)";
alert(convertDate(d));
You can do it like this
var date = new Date("Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)");
var year=date.getFullYear();
var month=date.getMonth()+1 //getMonth is zero based;
var day=date.getDate();
var formatted=year+"-"+month+"-"+day;
I see you're trying to format a date. You should totally drop that and use jQuery UI
You can format it like this then
var str = $.datepicker.formatDate('yy-mm-dd', new Date("Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)");
I found Web Developer's Notes helpful in formatting dates
For things like this it's often good to do a little testing in the browser console.
var date = new Date("Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)");
console.log(date.getFullYear() + '-' + date.getMonth()+1 + '-' + date.getDate())
Ensure you add + 1 to the result of getMonth() because it is zero based.
A similar question was asked here:
Where can I find documentation on formatting a date in JavaScript?
start_date="14 Feb 2020";
var new_startDate= new Date(start_date);
var date= moment(new_startDate).format('YYYY-MM-DD');
Answer: 2020-02-14
In here you have to use moment.js
The easiest way to convert is
new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: '2-digit'
}).format(new Date('Your Date'))
Just Replace 'Your Date' with your complicated date format :)
You can also use the Moment.js library, make sure to give it a search.
Few examples: moment().format('MMMM Do YYYY, h:mm:ss a');
moment().format('dddd');
A trifling refinement:
var date = new Date(value);
var year = date.getFullYear();
var rawMonth = parseInt(date.getMonth()) + 1;
var month = rawMonth < 10 ? '0' + rawMonth : rawmonth;
var rawDay = parseInt(date.getDate());
var day = rawDay < 10 ? '0' + rawDay : rawDay;
console.log(year + '-' + month + '-' + day);

Getting current time from the date object

function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(2), // get only two digits
month = datePart[1], day = datePart[2];
document.write(new Date(day+'/'+month+'/'+year));
}
formatDate ('2010/01/18');
When i print this i get Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time) but the system is actually 3:42 P.M
Use the current date to retrieve the time and include that in the new date. For example:
var now = new Date,
timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'),
dat = new Date('2011/11/30 '+timenow);
you must give the time:
//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11"));
//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11 23:23"));
What do you want? Just the time? Or do you want to define a format? Cu's the code expects this format for date: dd/mm/yyyy, changed this to yyyy/mm/dd
Try this:
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0],
month = datePart[1], day = datePart[2],
now = new Date;
document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds()));
}
formatDate ('2010/01/18')
Output:
Mon Jan 18 2010 11:26:21 GMT+0100
Passing a string to the Date constructor is unnecessarily complicated. Just pass the values in as follows:
new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10))
You're creating a Date() object with no time specified, so it's coming out as midnight. if you want to add the current date and time, create a new Date with no arguments and borrow the time from it:
var now = new Date();
var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10),
now.getHours(), now.getMinutes(), now.getSeconds())
No need to strip the last two characters off the year. "2010" is a perfectly good year.

Categories

Resources