How to display Firestore datetime [duplicate] - reactjs

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

In React how to convert UTC dateTime to more readable string inside the table

I have react component which showing records in the table. I have use 'useMemo' to define table structure and data. Some of its fields are date format which showing date like '2020-12-08T07:00:00Z'. I want to convert it to more friendly reading i.e. DD:MM:YYYY :Time?
Component
const EziSchedule = () =>{
const scheduleColumns = useMemo(
() => [
{
Header: "Schedule Id",
accessor: "eziScheduleId",
},
{
Header: "Start Time",
accessor: "startTime", //need to convert??
},
{
Header: "End Time",
accessor: "endTime", //need to convert??
},
],
[]
);
return (
<div>
<h3>Schedule</h3>
{props.searchCriteria&& props.searchCriteria.siteId!=0 &&
<TableItem
apiUrl={api.EziTrackerSchedule}
columns={scheduleColumns}
itemType={EcpItemTypes.EziTracker}
customParams= {props.searchCriteria}
selectedRow={selectedScheduleRow}
></TableItems>}
Error
I have tried below code in useMemo:[ ... but it throw exception
{
Header: "Login DateTime",
accessor: moment("loginDateTime","DD MM YYYY hh:mm:ss"),
},
If you want to output a variable with a string containing a date with momentjs you could go with moment(date).format(string). Please refer to the momentjs docs
moment().format(); // "2014-09-08T08:02:17-05:00" (ISO 8601, no fractional seconds)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA"); // "Sun, 3PM"
moment().format("[Today is] dddd"); // "Today is Sunday"
moment('gibberish').format('YYYY MM DD'); // "Invalid date"
or with a variable
const date = "2021-01-05";
const formatted = moment(date).format();
I can't comment, so...
Try this:
var d = new Date(YOUR DATE HERE);
var n = d.toLocaleString(CODE YOUR COUNTRY);
so, will be this way:
var d = new Date('2020-12-08T07:00:00Z');
var n = d.toLocaleString('pt-BR');
The result will be: 08/12/2020 04:00:00
Source (Here there are all the country codes):
https://www.w3schools.com/jsref/jsref_tolocalestring.asp

How to filter array from one date to another in Reactjs

I have an array of objects "mainData" like so:
0: {date: "2020-07-25T16:44:43.000Z"
description: "Qwerty"
id: 89329972},
1: {date: "2020-07-25T16:46:28.000Z"
description: "Place bins please"
id: 65586316},
2: {date: "2020-07-25T16:49:12.000Z"
description: "Solve sewerege problem"
id: 84687816},
3: {date: "2020-07-27T16:34:47.000Z"
description: "Test compl"
id: 56437370},
4: {date: "2020-07-28T08:40:34.000Z"
description: "Sewerage problem in my area"
id: 92402221},
5: {date: "2020-09-09T11:42:18.000Z"
description: "problem"
id: 25613902},
Now I am allowing the user to select from and to dates by using the mui datepicker. This is how I am receiving the values:
fromDate: Sat Jul 25 2020 11:43:00
toDate: Sat Aug 08 2020 11:43:00
Now I want to filter the array from this date to that date, including the from and to dates. I tried to do it this way but it just returns an empty array. I've put the code inside useEffect which is run every time toDate changes, Also I've used Moment to make the formats of both dates same:
useEffect( () => {
if (fromDate !== null && toDate !== null) {
setReportData(
mainData.filter(
(obj) =>{
return Moment(obj.date).format("DD MMM yyyy") >= Moment(fromDate).format("DD MMM yyyy") && Moment(obj.date).format("DD MMM yyyy") <= Moment(toDate).format("DD MMM yyyy")
}
)
)
}
},[toDate])
Edit
When I select a single date :
useEffect( () => {
if (oneDate !== null) {
setReportData(
mainData.filter(
(obj) =>{
return new Date(obj.date.substring(0, 19)).getTime() === oneDate.getTime()
}
)
)
}
},[oneDate])
Your object's date property can be parsed directly to Date object. So then you can use getTime.
Also, filter returns Date object.
So, you can change your code to this
useEffect( () => {
if (fromDate !== null && toDate !== null) {
setReportData(
mainData.filter(
(obj) =>{
return new Date(obj.date).getTime() >= fromDate.getTime() && new Date(obj.date).getTime() <= toDate.getTime()
}
)
)
}
},[toDate])
If you want to consider all dates to be of local timezone, then you need to remove the last part of each date's string in order for the parse method to consider each string as local timezone date.
So previous method becomes
useEffect( () => {
if (fromDate !== null && toDate !== null) {
setReportData(
mainData.filter(
(obj) =>{
return new Date(obj.date.substring(0, 19)).getTime() >= fromDate.getTime() && new Date(obj.date.substring(0, 19)).getTime() <= toDate.getTime()
}
)
)
}
},[toDate])
We can use moment.js too. By converting the moment to expected format.
In above case we have
Sat Jul 25 2020 11:43:00
Moment provides locale support format using llll, which is similar
to this one, usage as follow.
Initialize the format constant somewhere at top, after if statement;
const format = 'llll';
And just replace the filter return statement with :
return Moment(obj.date, format).unix() >= Moment(fromDate, format).unix() && Moment(obj.date, format).unix() <= Moment(toDate, format).unix()

Datepicker shows today's date when using format ''$filter('date')($scope.dt.datetime, 'd MMM, yyyy');' what to do? using angular js datepicker

I want date-picker to show the selected date in the format 15 Jun, 2019, but instead of the selected date it highlights today's date. But it shows the actual selected date when using the format 2019-06-15 instead.
I am using angularjs date-picker from this link
<input ng-show="toggleMe" type="text" readonly placeholder="Deadline"
class="date-picker" ng-datetime-picker="datePickerOptions"
ng-model="deadlineTask" ng-change="changeCurrentTime()" />
// in ng-model wanna show deadlineTask format here what to do that i show format in 'deadlinetask type format an it highlight selected date not the today's date'
angular.module('demo', ['ngDatetimePicker'])
.controller('datePickerCtrl',function($scope,$filter) {
$scope.dt = {};
var currentTime = new Date();
var year = currentTime.getFullYear();
var month = currentTime.getMonth() + 1;
var date = currentTime.getDate();
console.log(currentTime);
$scope.dt.datetime = '2019-06-15'; //showing correct date in this format
$scope.deadlineTask = $filter('date')($scope.dt.datetime, 'd MMM, yyyy');
//showing today's date in this format this format i want but not highlighting the selected date instead of it showing today's date
You want the datepicker to always be using a date format that you define?
Based on the documentation the datepicker you have chosen does not seem to be able to show the format '15 Jun, 2019'. Maybe have a look at another AngularJs datetime picker if that is the case such as this one
To test it I see from your html that you should have an object called datePickerOptions on $scope?
If that is the case define a property called dateFormat within the datePickerOptions object and give it a string value e.g. 'MM, YYYY'
Here you can see this is how they define the date format of an input field:
Here are the formatting options listed:
YYYY: Year, 4 digit
YY: Year, 2 digit
MM: Month, 01-12
M: Month, 1-12
DD: Day, 01-31
D: Day, 1-31
HH: Hour using 12-hour clock 01-12
H: Hour using 12-hour clock 1-12
hh: Hour using 24-hour clock 00-23
h: Hour using 24-hour clock 0-23
mm: Minute, 00-59>
m: Minute, 0-59
tt: am/pm
TT: AM/PM
<input ng-show="toggleMe" type="text" readonly placeholder="Deadline" class="date-picker" ng-datetime-picker="datePickerOptions" ng-model="dt.datetime" ng-change="changeCurrentTime()" />
<script>
angular.module('demo', ['ngDatetimePicker']).
controller('datePickerCtrl', function($scope,$filter) {
$scope.dt = {};
var currentTime = new Date();
var year = currentTime.getFullYear();
var month = currentTime.getMonth() + 1;
var date = currentTime.getDate();
currentTime = year + "-" + month + "-" +"29"+ " 9:00";
$scope.dt.datetime = '2019-06-15';
$scope.deadlineTask = $filter('date')($scope.dt.datetime, 'd MMM, yyyy');
$scope.toggleMe = false;
$scope.datePickerOptions = {
"closeOnSelected": true,
"firstDayOfWeek": 1,
"dateOnly": true
};
$scope.datetimePickerOptions = {
"closeOnSelected": true,
"firstDayOfWeek": 1
};
});

React Native Create Components with multiple condition

I have a data structure like this:
const _ = require('lodash');
const bills = [
{year:2021, month:5, bill:'bill in 2021 may'},
{year:2018, month:1, bill:'bill in 2018 jan'},
{year:2019, month:1, bill:'bill in 2019 jan'},
{year:2018, month:2, bill:'bill in 2018 feb'},
{year:2019, month:10,bill:'bill in 2019 oct'},
{year:2019, month:2, bill:'bill in 2019 feb'},
{year:2019, month:6, bill:'bill in 2019 jun'},
{year:2020, month:11,bill:'bill in 2020 nov'}
];
and I want to display like below using Text or Card component of native-base
2018
1
bill in 2018 jan
2
bill in 2018 feb
2019
1
bill in 2019 jan
2
bill in 2019 feb
6
bill in 2019 jun
10
bill in 2019 oct
2020
11
bill in 2020 nov
2021
5
bill in 2021 may
My codes are below using lodash library to generate above and display in the terminal
// sort the data first
let arrSortedTasks = _.orderBy(tasks, ['year', 'month'],['asc']);
// get all the different year from the data
let arrUniqYear = _.uniqBy(arrSortedTasks, 'year');
// get all the different month from the data
let arrUniqMonth = _.uniqBy(arrSortedTasks, 'month');
// take out only the value of the year
arrUniqYear =_.map(arrUniqYear, 'year');
// take out only the value of the month
arrUniqMonth =_.map(arrUniqMonth, 'month');
let taskList = '';
for (let year of arrUniqYear) {
console.log(year);
for (let month of arrUniqMonth) {
let displayMonth = false;
for (let obj of arrSortedTasks) {
if (obj.year === year && obj.month === month) {
taskList = taskList + obj.task;
displayMonth = true;
}
}
if (displayMonth) {
console.log(" " + month);
}
if (taskList.length > 0) {
console.log(" " + taskList);
}
taskList = '';
}
}
How can we display the components in react-native with native-base? SO here don't let me post if too many code sigh. I tried a few ways buy got errors and can't figure out.
I end up using array as a return object in rendering
renderBillsSection() {
const { bills } = this.props;
if(bills || bills.length > 0 ) {
let arrSortedTasks = _.orderBy(tasks, ['year', 'month'],['asc']);
let arrUniqYear = _.uniqBy(arrSortedTasks, 'year');
let arrUniqMonth = _.uniqBy(arrSortedTasks, 'month');
let billList = '', arr = [], yearIndex = 0, monthIndex = 0, billIndex = 0;
arrUniqYear = _.map(arrUniqYear, 'year');
arrUniqMonth = _.map(arrUniqMonth, 'month');
for (let year of arrUniqYear) {
arr.push(<Text key="{yearIndex}">{year}</Text>)
yearIndex++
for (let month of arrUniqMonth) {
let displayMonth = false;
for (let obj of arrSortedTasks) {
if (obj.year === year && obj.month === month) {
billList = billList + obj.task
displayMonth = true
}
}
if (displayMonth) {
arr.push(<Text key="{monthIndex}" style={{marginLeft:10}}>{month}</Text>)
monthIndex++
}
if (billList.length > 0) {
arr.push(<Text key="{taskIndex}" style={{marginLeft:20}}>{billList}</Text>)
billIndex++
}
billList = '';
}
}
return arr;
}
}
not sure about how you are planning to render it in UI, but if you want to have the data structure like this, you need to group it (and sort by monhts if its not already sorted)
_(bills).groupBy('year').map((v,k)=> ({year: k, docs: _.sortBy(v,'month')})).value()
it will give you another array where you have year, abd docs as nested array holding all the documents of that year, so that you can agaib have another repeat on that.
const bills = [
{year:2021, month:5, bill:'bill in 2021 may'},
{year:2018, month:1, bill:'bill in 2018 jan'},
{year:2019, month:1, bill:'bill in 2019 jan'},
{year:2018, month:2, bill:'bill in 2018 feb'},
{year:2019, month:10,bill:'bill in 2019 oct'},
{year:2019, month:2, bill:'bill in 2019 feb'},
{year:2019, month:6, bill:'bill in 2019 jun'},
{year:2020, month:11,bill:'bill in 2020 nov'}
]
let groupedDoc = _(bills).groupBy('year').map((v,year)=> ({year, docs: _.sortBy(v,'month')})).value();
console.log(groupedDoc);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
Here is a working snippet:
I think you should do :
const gropuByYear = _.groupBy(bills,'year');
console.log(_.map(groupByYear, groups =>
groups.forEach(group=>(<View> {obj.bill}</View>)))
even you can orderBy year desc first then do the loop good luck
You need to take a look at SectionList of React Native.
Checkout this example and cuiyueshuai for more practical example.
SectionList Demo:
<SectionList
renderItem={({ item, index, section }) => <Text key={index}>{item}</Text>}
renderSectionHeader={({ section: { title } }) => <Text style={{ fontWeight: 'bold' }}>{title}</Text>}
sections={[
{ title: 'Title1', data: ['item1', 'item2'] },
{ title: 'Title2', data: ['item3', 'item4'] },
{ title: 'Title3', data: ['item5', 'item6'] },
]}
keyExtractor={(item, index) => item + index} />

Angular to display last 12 months dates

I am trying to write simple ng-repeat that displays a list of the last 12 months, from today.
So for example, if i load my application today (May 2014), i will have a list of:
May 2014
Apr 2014
Mar 2014
Feb 2014
Jan 2014
Dec 2013
Nov 2013
Oct 2013
Sep 2013
Aug 2013
Jul 2013
Jun 2013
If i was to view on say, September 2014, then the list would display as:
Sep 2014
Aug 2014
Jul 2014
Jun 2014
May 2014
Apr 2014
Mar 2014
Feb 2014
Jan 2014
Dec 2013
Nov 2013
Oct 2013
HTML:
<div ng-app="">
<div ng-controller="Ctrl">
<li ng-repeat="currMonth in months">{{currMonth}}</li>
</div>
</div>
JS:
function Ctrl($scope) {
$scope.months = [
"01 - Jan",
"02 - Feb",
"03 - Mar",
"04 - Apr",
"05 - May",
"06 - Jun",
"07 - Jul",
"08 - Aug",
"09 - Sep",
"10 - Oct",
"11 - Nov",
"12 - Dec"
];
$scope.month = 'null';
}
The logic is fairly simple and really not anything angularjs related. That being said, I wanted to try it out for myself and this is what I came up with.
angular.module('test', []).controller('Ctrl', function($scope) {
var date = new Date();
var months = [],
monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
for(var i = 0; i < 12; i++) {
months.push(monthNames[date.getMonth()] + ' ' + date.getFullYear());
// Subtract a month each time
date.setMonth(date.getMonth() - 1);
}
$scope.months = months;
});
Here's the jsfiddle I used to create it.
Since we are using angular, take advantage on $filter directives
angular.module('test', []).controller('Ctrl', function($scope, $filter) {
$scope.premonths = 12;
$scope.getMonths = function(){
$scope.months = [];
var today = new Date();
var endDate = new Date()
endDate.setMonth(endDate.getMonth() - $scope.premonths)
for(var d=today;d > endDate;d.setMonth(d.getMonth() - 1)) {
$scope.months.push({month:($filter('date')(d, 'MMMM')),year:$filter('date')(d, 'yyyy')})
}
}
$scope.getMonths();
});
input {
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app='test'>
<body ng-controller='Ctrl'>
Get last <input ng-model='premonths' ng-change='getMonths()'> months
<ul>
<li ng-repeat='month in months'>
{{month.month}} - {{ month.year}}
</li>
</ul>
</body>
</html>

Resources