Formatting date React - css

How can I arrange the date in the proper format?
On the screen the date wrong, it shows 32/03/2020 but day 32 does not exist.
The correct format date is on the image below.
I am new with Reactjs, what has gone wrong in my code and how can I solve it?
My code is below:
class Chamado extends Component {
constructor(props) {
super(props);
this.state = {
offset: 0,
pageCount: this.props.chamados.length / this.props.perPage,
};
this.formatDate = this.formatDate.bind(this);
this.handlePageClick = this.handlePageClick.bind(this);
}
formatDate(date) {
const dateObject = new Date(date);
const day =
dateObject.getDate() + 1 < 10
? '0' + (dateObject.getDate() + 1)
: dateObject.getDate() + 1;
const month =
dateObject.getMonth() + 1 < 10
? '0' + (dateObject.getMonth() + 1)
: dateObject.getMonth() + 1;
const year = dateObject.getFullYear();
const formattedString = `${day}/${month}/${year}`;
return formattedString;
}
handlePageClick(data) {
let selected = data.selected;
let offset = Math.ceil(selected * this.props.perPage);
this.setState({
offset: offset,
});
}
render() {
const props = this.props;
return (
<SC.Container>
<SC.Title>
Histórico de <b>Chamados</b>
{this.props.chamados.length !== undefined && (
<SC.Add
title="Abrir um novo chamado"
onClick={(event) => props.setViewAbrirChamados(true)}
>
<GoPlus size="21px" color="#FFF" />
</SC.Add>
)}
</SC.Title>
<SC.List>
{this.props.chamados.length !== undefined ? (
<React.Fragment>
{props.chamados.length > 0 &&
props.chamados.map((item, index) => {
const maxOffset = this.state.offset + (props.perPage - 1);
return (
index >= this.state.offset &&
index <= maxOffset && (
<SC.Item key={item.id}>
<SC.Info>
<SC.Details>
<p>
<b>
{item.id} |{' '}
{item.titulo || item.categoria.descricao}
</b>
</p>
<p>
{this.formatDate(item.data_abertura)} -{' '}
{item.hora_abertura}
</p>
</SC.Details>
</SC.Info>
<SC.Buttons
onClick={(event) => {
props.setViewChamadoInfo(true, item.id);
}}
>
<button>
<FaInfo size="24" color="#fff" />
</button>
</SC.Buttons>
</SC.Item>
)
The format is on the image below:

What you need is a padding function something like below
const padNumber = (number) => {
if (number.toString().length === 1) return `0${number}`;
return number;
};
const formatDate = (date) => {
const dateObject = new Date(date);
const day = dateObject.getDate();
const month = dateObject.getMonth() + 1;
const year = dateObject.getFullYear();
const formattedString = `${padNumber(day)}/${padNumber(month)}/${year}`;
return formattedString;
};
Still the easiest way would be using moment.js

Related

howto debug nuxt instance unavailable?

i'm working on a nuxt 3 project.
i've created a composable useAvailabilityRoom.ts but suddendy, it stopped working to throw this error :
Error: nuxt instance unavailable 10:42:04
at Module.useNuxtApp (/Users/chilperic/Sites/cabinetpartage/node_modules/nuxt/dist/app/nuxt.mjs:165:13)
at Module.useAsyncData (/Users/chilperic/Sites/cabinetpartage/node_modules/nuxt/dist/app/composables/asyncData.mjs:24:38)
at Module.useFetch (/Users/chilperic/Sites/cabinetpartage/node_modules/nuxt/dist/app/composables/fetch.mjs:52:43)
at Module.__vite_ssr_exports__.default (/Users/chilperic/Sites/cabinetpartage/composables/useUsers.ts:6:55)
at Module.__vite_ssr_exports__.default (/Users/chilperic/Sites/cabinetpartage/composables/useRoomAvailability.ts:61:55)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async setup (/Users/chilperic/Sites/cabinetpartage/pages/salles/[idLocation]/[idRoom].vue:59:12)
my call in page component
try {
const roomAvailability = await useRoomAvailability(route.params.idRoom);
} catch (e) {
console.log(e);
}
my composable code
class RoomSchedule {
roomId: String = "";
days = [
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday",
];
monday = [];
tuesday = [];
wednesday = [];
thursday = [];
friday = [];
saturday = [];
sunday = [];
constructor(roomId: String) {
this.roomId = roomId;
}
checkAvailability(profile) {
for (let d in this.days) {
if (
profile.weekly_schedule[this.days[d]] !== false &&
profile.weekly_schedule[this.days[d]][this.roomId] !==
undefined &&
profile.weekly_schedule[this.days[d]][this.roomId] == true
) {
// on crée un objet de rendez-vous
const apt = {
begins_at: "07:00",
ends_at: "20:00",
name: profile.first_name + " " + profile.last_name,
job: profile.job,
user: profile.user_id,
};
// on compare les deux objets pour ne pas insérer un doublon
if (
this[this.days[d]].find(
(element) =>
JSON.stringify(element) === JSON.stringify(apt)
) == undefined
) {
this[this.days[d]].push({
begins_at: "07:00",
ends_at: "20:00",
name: profile.first_name + " " + profile.last_name,
job: profile.job,
user: profile.user_id,
});
}
} else {
// console.log("rien pour " + this.days[d]);
}
}
return true;
}
}
export default async (roomId: String) => {
// récupérer la dispo de la salle
const locationsObject = await useLocations();
const locations = Object.values({ ...locationsObject });
const room = locations.filter((el) => el.identifier == roomId);
const roomAvailability = toRaw(room[0]).availability;
let Schedule = new RoomSchedule(roomId);
// récupérer les résa des thérapeutes en bail
const profiles = await useUsers();
for (let av in profiles) {
// on parcourt les jours et on regarde s'il y a des thérapeutes au bail
for (let day in profiles[av].weekly_schedule) {
await Schedule.checkAvailability(profiles[av]);
}
}
return Schedule;
};
If i log the checkAvailability content, i have the right data.
I don't understand how to fix this error. Hope you can see what's wrong.

Google sheet + App Script : Rename every sheet if it meet criteria

Hi I'm using this script to rename every sheet by inserting 'Copy of' in front of the existing sheet name where the text in cell 'B36' = 'SAFETY ANALISIS' and the date from cell 'K3'is older then 30 days. My issue is having to do with the date I can't quite figure how to do it. Cell 'K3' cell are in this format "1-Aug-2021" I think I need to convert the date in 'K3' to a number format.
Any help would be greatly appreciated
function getSheet() {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var sum = 0;
for (var i = 0; i < sheets.length ; i++ ) {
var sheet = sheets[i];
var date = new Date();
var ageInDays = 30;
var threshold = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate() - ageInDays)
.getTime();
var val = sheet.getRange('K3').getValue();
var val2 = sheet.getRange('B36').getValue();
if (val >= threshold && val2 == 'SAFETY ANALYSIS') {
var sheetName = sheet.getName()
sheet.setName('Copy Of '+sheetName)
}
}
}
You may want to wrap the value you get from cell K3 in a Date() constructor. That should work with spreadsheet dates as well as text strings that look like dates.
I think you have the comparison in val >= threshold the wrong way around. Try something like this:
function renameOldSafetyAnalysisSheets() {
const timeLimit = 30 * 24 * 60 * 60 * 1000; // 30 days
const now = new Date();
const sheets = SpreadsheetApp.getActive().getSheets();
sheets.forEach(sheet => {
if (sheet.getRange('K3').getValue() !== 'SAFETY ANALYSIS') {
return;
}
const date = new Date(sheet.getRange('B36').getValue());
if (!date.getTime()
|| now.getTime() - date.getTime() < timeLimit) {
return;
}
try {
sheet.setName('Copy of ' + sheet.getName());
} catch (error) {
;
}
});
}
function getSheet() {
const shts = SpreadsheetApp.getActive().getSheets();
let d = new Date();
let ageInDays = 30;
let threshold = new Date(d.getFullYear(),d.getMonth(),d.getDate() - ageInDays).valueOf();
shts.forEach(sh => {
let val = new Date(sh.getRange('K3').getValue()).valueOf();
let val2 = sh.getRange('B36').getValue();
if (val <= threshold && val2 == 'SAFETY ANALYSIS') {
sh.setName('Copy Of ' + sh.getName())
}
});
}

'Timestamp' is not a subtype of type 'int' - Flutter - Firebase Firestore

I got an error when I try to get Time set data from Cloud Firestore.
I think if I set timestampsInSnapshots: true then the issue will be fixed, but I can't set it because I use cloud_firestore: ^0.16.0 so I couldn't found how can I do this. if I use cloud_firestore: ^0.8.2+1 then I can configure the Firestore's settings. But I wanna set this configuration in version 0.16.0
About Issue:
The following _TypeError was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#ec8a0):
type 'Timestamp' is not a subtype of type 'int'
The relevant error-causing widget was
StreamBuilder<QuerySnapshot>
lib/…/main/profile.dart:66
When the exception was thrown, this was the stack
#0 _ProfileState.buildExamHistoryList.<anonymous closure>.<anonymous closure>
lib/…/main/profile.dart:97
#1 MappedListIterable.elementAt (dart:_internal/iterable.dart:411:31)
#2 ListIterator.moveNext (dart:_internal/iterable.dart:340:26)
#3 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:188:27)
#4 new _GrowableList.of (dart:core-patch/growable_array.dart:150:28)
...
enter image description here
The stream where I wanna set my data from firestore:
Widget buildExamHistoryList() {
return StreamBuilder<QuerySnapshot>(
stream: usersRef.doc(widget.userID).collection('examResults').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.hasError) {
return Center(
child: Text("Something Went Wrong"),
);
}
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Container(
padding: EdgeInsets.only(top: 100),
child: Center(
child: SpinKitFadingCircle(
color: Colors.black,
size: 50,
),
),
);
break;
default:
return Column(
children: [
ListView(
shrinkWrap: true,
children: snapshot.data.docs.map((doc) {
return Padding(
padding: const EdgeInsets.all(10),
child: ExamHistoryCard(
correctAnswersCount: doc['correctAnswersCount'],
incorrectAnswersCount: doc['incorrectAnswersCount'],
date: _examHistoryService.readTimestamp(doc['date']),
),
);
}).toList(),
),
],
);
}
},
);
}
and that is my readTimestamp function:
String readTimestamp(int timestamp) {
var now = DateTime.now();
var format = DateFormat('HH:mm a');
var date = DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
var diff = now.difference(date);
var time = '';
if (diff.inSeconds <= 0 ||
diff.inSeconds > 0 && diff.inMinutes == 0 ||
diff.inMinutes > 0 && diff.inHours == 0 ||
diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date);
} else if (diff.inDays > 0 && diff.inDays < 7) {
if (diff.inDays == 1) {
time = diff.inDays.toString() + ' Dünen';
} else {
time = diff.inDays.toString() + ' Gün Önce';
}
} else {
if (diff.inDays == 7) {
time = (diff.inDays / 7).floor().toString() + ' Hefte Önce';
} else {
time = (diff.inDays / 7).floor().toString() + ' Hefte Önce';
}
}
return time;
}
The dates you get from firebase in doc['date'] is a Timestamp, not an int. You can transform it into a Date by using toDate() method or to milliseconds since epoch with toMillis() like this:
final Timestamp timestamp = doc['date'];
final DateTime date = timestamp.toDate();
final int millis = timestamp.toMillis()
Also be sure to declare the correct type you are going to be passing to your readTimestamp function:
String readTimestamp(Timestamp timestamp) {}
or
String readTimestamp(DateTime date) {}
or
String readTimestamp(int millis) {}
Try this
String readTimestamp(Timestamp timestamp) {
var now = DateTime.now();
var format = DateFormat('HH:mm a');
var date = timestamp.toDate();
var diff = now.difference(date);
var time = '';
if (diff.inSeconds <= 0 ||
diff.inSeconds > 0 && diff.inMinutes == 0 ||
diff.inMinutes > 0 && diff.inHours == 0 ||
diff.inHours > 0 && diff.inDays == 0) {
time = format.format(date);
} else if (diff.inDays > 0 && diff.inDays < 7) {
if (diff.inDays == 1) {
time = diff.inDays.toString() + ' Dünen';
} else {
time = diff.inDays.toString() + ' Gün Önce';
}
} else {
if (diff.inDays == 7) {
time = (diff.inDays / 7).floor().toString() + ' Hefte Önce';
} else {
time = (diff.inDays / 7).floor().toString() + ' Hefte Önce';
}
}
return time;
}
Timestamp from Firebase will be formatted as Timestamp or Map.
Here DatetimeConverter taking care of the conversion from/to json from Firebase Firestore and Cloud Functions:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
class DatetimeConverter implements JsonConverter<DateTime, dynamic> {
const DatetimeConverter();
#override
dynamic toJson(DateTime object) {
return object != null
? Timestamp.fromDate(object)
: FieldValue.serverTimestamp();
}
#override
DateTime fromJson(dynamic val) {
Timestamp timestamp;
if (val is Timestamp) {
// the firestore SDK formats the timestamp as a timestamp
timestamp = val;
} else if (val is Map) {
// cloud functions formate the timestamp as a map
timestamp = Timestamp(val['_seconds'] as int, val['_nanoseconds'] as int);
}
if (timestamp != null) {
return timestamp.toDate();
} else {
// Timestamp probably not yet written server side
return Timestamp.now().toDate();
}
}
}

Disable all weekends and specific days plus enable mothers day

I have the following code already working well in functions.php - I want to enable mothers day though (12 may 2019) which falls on a Sunday. How to do I add this to the return string?
function custom_adjust_datepicker_range () {
if ( is_checkout() ) {
?>
<script type="text/javascript">
var disabledDays = [
"1-1-2019","1-1-2020","2-1-2019","28-1-2019","27-1-2020","4-3-2019","2-3-2020","19-4-2019","10-4-2020","22-4-2019","13-4-2020","25-4-2019","25-4-2020","27-4-2020","3-6-2019","1-6-2019","30-9-2019","28-9-2020","25-12-2018","25-12-2019","25-12-2020","26-12-2018","26-12-2019","26-12-2020","27-12-2018"
];
jQuery( "#delivery_date" ).datepicker({
minDate: 2,
beforeShowDay: function(date) {
var day = date.getDay();
var string = jQuery.datepicker.formatDate('d-m-yy', date);
var isDisabled = (jQuery.inArray(string, disabledDays) != -1);
return [(day != 1 && day != 0 && !isDisabled), ''];
}
});
</script>
<?php
}
} // End custom_adjust_datepicker_range()
add_action( 'wp_footer', 'custom_adjust_datepicker_range', 50 );
Consider the following example.
jQuery(function() {
var disabledDays = [
"1-1-2019", "1-1-2020", "2-1-2019", "28-1-2019", "27-1-2020", "4-3-2019", "2-3-2020", "19-4-2019", "10-4-2020", "22-4-2019", "13-4-2020", "25-4-2019", "25-4-2020", "27-4-2020", "3-6-2019", "1-6-2019", "30-9-2019", "28-9-2020", "25-12-2018", "25-12-2019", "25-12-2020", "26-12-2018", "26-12-2019", "26-12-2020", "27-12-2018"
];
var dtf = 'd-m-yy';
function getMothersDay(y) {
var mayFirst = new Date(y, 4, 1);
var dayOfWeek = mayFirst.getUTCDay();
var firstSunday;
if (dayOfWeek == 0) {
firstSunday = mayFirst;
} else {
firstSunday = new Date(y, 4, 1 + (7 - dayOfWeek));
}
var mothersDay = new Date(y, 4, firstSunday.getDate() + 7);
return mothersDay;
}
function isMothersDay(dt) {
return (jQuery.datepicker.formatDate(dtf, dt) == jQuery.datepicker.formatDate(dtf, getMothersDay(dt.getFullYear())));
}
jQuery("#delivery_date").datepicker({
minDate: 2,
beforeShowDay: function(date) {
var day = date.getDay();
var string = jQuery.datepicker.formatDate(dtf, date);
var isDisabled = jQuery.inArray(string, disabledDays);
var result = [
true,
"",
""
];
switch (true) {
case isMothersDay(date):
// Mother's Day
result = [
true,
"mothers-day",
"Mother's Day"
];
break;
case (isDisabled >= 0):
// Disable Days
result[0] = false;
break;
case (day == 0):
case (day == 6):
// Weekends
result[0] = false;
break;
}
return result;
}
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Delivery Date: <input type="text" id="delivery_date"></p>
See More: How to calculate Mother’s Day in JavaScript
This example was based on first Google search result I performed. In the future, you may want to search for basic examples.
This is not adjusted for WordPress, so you will need to adapt the code to your needs.
You have 3 basic checks:
Is the date Mother's Day
Is the date in the array of dates
Is the date a weekend day
You might have other scenarios arise so using a switch() might be easier overall. I move from the least common condition to the most common condition. You could add more and only check if it's Mother's Day if the month is May and they day of the month is within the first 2 weeks: (date.getMonth() == 4 && date.getDate() < 15).
Hope this helps.

Extjs4 multigrouping header value css

I am using the Extjs4 multigrouping plugin from here.
I have used it successfully, however i want to show the summary of the totals of each column within the group header itself . how do i set up the appropriate CSS for that ?
In Multigrouping.js
getFragmentTpl: function() {
var me = this;
return {
indentByDepth: me.indentByDepth,
depthToIndent: me.depthToIndent,
renderGroupHeaderTpl: function(values, parent) {
return Ext.XTemplate.getTpl(me, 'groupHeaderTpl').apply(values, parent);
//var z = new Ext.XTemplate('{name} ({rows.grouplength})');
//return z.apply(values, parent);
}
};
},
In my grid
features: [
{
ftype:'multigrouping',
groupHeaderTpl: [
'{[this.readOut(values)]}',
{
readOut:function(values) {
debugger;
var sum1 =0 ,sum2=0,sum3=0;
for( var i = 0 ; i< values.records.length ; i++)
{
var val = parseFloat(values.records[i].data.d2012.mp);
sum1 += isNaN(val) ? 0.0 : val;
val = parseFloat(values.records[i].data.d2013.mp);
sum2 += isNaN(val) ? 0.0 : val;
val = parseFloat(values.records[i].data.d2014.mp);
sum3 += isNaN(val) ? 0.0 : val;
}
return values.name + '(' + values.records.length + ')' + ' ' + sum1.toFixed(2) + ' ' + sum2.toFixed(2) + ' ' + sum3.toFixed(2);
}
}
]
},
had to resort to a few hacks to get this to work. still waiting on an official answer.
The main reason i had to do this and not use the multigrouping summary is because
- i want to limit the number of records from the server. I can do some smart grouping of
my business objects at the server side.
- the main reason to do this is because of IE8's performance on larger sets of data.
- had already tried the extjs4 tree grid component which works well on chrome but had performance issues on IE8.
the hack is to
a) use an array property in the grid to store the dom elements which i want to manipulate
b) use a boolean to know when the layout is completed the first time
b) add listeners for afterlayout ( when your app can do an Ext.get('..dom element..') you know you are done )
The listener :
listeners :
{
afterlayout : function(eopts)
{
var x = this.mOwnArray;
if(!this.loadedwithVals && x.length > 0)
{
for(var i =0 ; i<x.length ; i++)
{
var dom = Ext.get(x[i].id);
var theId = dom.id;
theId = theId.match(/\d+/)[0];
var title = dom.query("td[class='x-grid-cell x-grid-cell-first']");
title[0].className = 'x-grid-cell x-grid-cell-gridcolumn-' + theId + ' x-grid-cell-first';
title[0].colSpan=1;
var groupedHeader = dom.query("div[class='x-grid-group-title']");
groupedHeader[0].innerHTML = x[i].name + '(' + x[i].length + ')';
for(var year=2012;year<=2018;year++)
{
var t = "t"+year;
var someText1 = '<td class=" x-grid-cell x-grid-cell-numbercolumn">';
var someText2 = '<div class="x-grid-cell-inner " style="text-align: left; ;">';
var someText3 = '<div class="x-grid-group-title">' + x[i].total[t] + '</div></div></td>';
var someText = someText1 + someText2 + someText3;
dom.insertHtml("beforeEnd",someText);
}
}
this.loadedwithVals = true;
}
}
And the feature as in
features: [
{
ftype:'multigrouping',
startCollapsed : true,
groupHeaderTpl: [
'{[this.readOut(values)]}',
{
readOut:function(values) {
var header = new Object();
header.id = values.groupHeaderId;
header.sum = [];
header.total = new Object();
for(var year = 2012 ; year <= 2018 ; year++)
{
var t = "t"+year;
header.total[t] = [];
}
// all the records in this header
for( var i = 0 ; i< values.records.length ; i++)
{
// for all the 'years' in this record
for(var year=2012;year<=2018;year++)
{
var d = "d"+year;
var ct = "t" + year;
var arecord = values.records[i].data;
var val = parseFloat(arecord[d].mp);
val = isNaN(val) ? 0.0 : val;
Ext.Array.push(header.total[ct],val);
}
}
// push the sum of the records into its top level group
for(var year = 2012 ; year <= 2018 ; year++)
{
var t = "t"+year;
var sum = Ext.Array.sum(header.total[t]);
header.total[t] = sum.toFixed(2);
}
header.name = values.name;
header.length = values.records.length;
var headerName = values.name;
if(values.hasOwnProperty('parent'))
{
var parent = values.parent;
headerName = headerName.replace(parent,'');
}
header.name = headerName;
header.length = values.records.length;
Ext.Array.push(grid.mOwnArray,header);
// really not used
return values.name + '(' + values.records.length + ')';
}
}
]
},
]

Resources