Display Date (not time) from Firestore Timestamp - javascript

I'm pulling a timestamp from a Firestore database, and I only want to display the date to the user. The original timestamp is
Timestamp(seconds=1555477200, nanoseconds=0)
I've tried a few variations to get the Date, but they all have the same output-
Due: Wed Apr 17 2019 06:10:21 GMT-0500 (Central Daylight Time)
<p>Due: ${Date(dueDate)}<br>
<p>Due: <time>${Date(dueDate)}</time><br>
<p>Due: <time type="date">${Date(dueDate)}</time><br>
How do I cut off the time part of the timestamp?
(Ideally, I'd want "April 17, 2019", but if the day is in there that's fine too)

If you have a particular format for date, you can do
function getDate (timestamp=Date.now()) {
const date = new Date(timestamp);
let dd = date.getDate();
let mm = date.getMonth()+1; //January is 0!
const yyyy = date.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
// Use any date format you like, I have used YYYY-MM-DD
return `${yyyy}-${mm}-${dd}`;
}
getDate(1555477200000);
// -> 2019-04-17
Alternatively, you can also do:
const time = new Date(1555477200000);
// -> Wed Apr 17 2019 10:30:00 GMT+0530 (India Standard Time)
const date = time.toDateString();
// -> Wed Apr 17 2019
P.S: I have used ES6 here. If you are working on ES5, use babel's online transpiler to convert.
Link: https://babeljs.io/repl

You can do
var time= timeStampFromFirestore.toDate();
console.log(time);
console.log(time.toDateString());
See the full documentation :
toDateString()
toDate()

You can use Date.toLocaleString() like this:
new Date(date).toLocaleString('en-EN', { year: 'numeric', month: 'long', day: 'numeric' });
const timestamp = 1555477200000;
console.log(
new Date(timestamp).toLocaleString('en-EN', { year: 'numeric', month: 'long', day: 'numeric' })
);

Simply use moment.js and use your required format
date = moment();
console.log(date.format("MMMM D, YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>

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};

How to convert string into date in js [duplicate]

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)"));

How to convert a non local javascript date timezone to UTC?

How can I convert a date to UTC from a specific timezone?
In javascript you can convert a local date to utc and create a date from a date string or utc string.
The intl built in functions allow you to convert a datetime to a timezone, but not back to utc. I could not find any specific questions on this amazingly all others say local time.
I know that in moment you can convert a UTC from a timezone, like this:
var now = moment();
console.log(now.format('YYYY-MM-DD HH:mm:ss'))
console.log(now.utc().format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").utc().format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").tz("Asia/Tokyo").format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").tz("Asia/Tokyo").utc().format('YYYY-MM-DD HH:mm:ss'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.25/moment-timezone-with-data.min.js"></script>
The utcs should match. Aside from using moment, what other ways (browser, node, libraries) are there to convert a date considering it's in a timezone that is not local in the browser using js to utc? Doesn’t need to be vanilla js.
Here was my javascript native vanillajs solution using Intl.DateTimeFormat()
Basically I get the difference in the timezone specified and the local time. I add that difference then set return the utc.
/**
* take a date of assumed timezone and convert to utc
*
* #param {*} d
* #param {*} tz
* #returns
*/
function tzUTC(d, tz) {
// first calculate tz difference
// use passed in date to get timezone difference as close to that day.
var date = new Date(d);
var options = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
timeZone: tz
};
var tzDate = new Intl.DateTimeFormat('en-US', options).format(date)
var diff = date - new Date(tzDate);
var minutes = Math.floor((diff / 1000) / 60);
var localTime = new Date(d);
localTime.setMinutes(d.getMinutes() + minutes);
return localTime.toUTCString();
}
var d = new Date("5/18/2019, 07:49:13");
// Fri May 17 2019 17:49:13 GMT-0400 (Eastern Daylight Time)
// utc should be Fri, 17 May 2019 21:49:13 GMT"
//
console.log("d:" + d)
console.log("tzUTC:" + tzUTC(d, 'Australia/Sydney'))
d = new Date("5/17/2019, 14:53:21");
console.log("d:" + d)
// Fri May 17 2019 17:53:21 GMT-0400 (Eastern Daylight Time)
// utc "Fri, 17 May 2019 21:53:21 GMT"
console.log("tzUTC:" + tzUTC(d, 'America/Los_Angeles'))

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