formatting date into ISO string for `react-admin` - javascript

My API needs the date to be in ISO format. I have tried multiple ways to get that in react-admin DateInput component I'm still not able to get the date in that format. Either the input element gets frozen, or invalid date error is thrown or the date is still getting in YYYY-MM-DD format. I'm trying to use parse and format props but the input element gets frozen for some reason.
const dateParser = (v: string) => {
return new Date(v?.split('T')[0]);
};
const dateFormatter = (v: Date) => {
if (!(v instanceof Date) || Number.isNaN(v)) return;
const formatted = v.toISOString();
return formatted;
};
<DateInput source="pub_date" format={dateFormatter} defaultValue={new Date()} parse={dateParser} label="Publish Date" />

In my opinion, you have confused functions: format - is used when displaying data, parse - when saving data in a record.

Related

Can't convert timestamp to date properly in Javascript

I use mongodb as my database and in that db I have a timestamp field but I haven't seen any format similar to that. Some of them are:
1657479170.7300725
1657479170.7301126
1657479170.7301197
1657479170.9120467
1657479170.932398
When i try to convert this to normal date format (YYYY-MM-DD) I get the correct date. For example the converted date of the first timestamp above is:
10.07.2022 21:52:50
However when I try to convert it in javascript I get:
1970-01-20 06:24:39
which is definitely not correct value.
My code for the conversion :
ConvH.forEach(conv => {
conv.tracker.events.forEach(element => {
console.log(parseFloat( parseFloat(element.timestamp.toFixed(4))), moment(new Date( parseFloat( element.timestamp.toFixed(4)))).format("YYYY-MM-DD HH:mm:ss"));
element.timestamp = new Date(element.timestamp).toLocaleString();
})
});
Note : new Date(element.timestamp).toLocaleString(); gives the same thing :/
Try this: new Date(timestamp.getHighBits() * 1000)

I want to write test cases for function with parameter using jest

I have one function which is accepting one parameter in yyyy-mm-dd format. I am taking todays date and comparing that date with date received in parameter.
I want to write test cases using jest, Firstly it should check date passed in parameter is in yyyy-mm-dd format.
So my function is roughly looks like:
function dateFunction(parameter in yyyy-mm-dd format){
today = new Date() // it is taking todays date.
convertedDate = converting parameter date into date format.
if (today === convertedDate){
// then do something
}
else {
// do something
}
}
test("The function parameter should be in yyyy-mm-dd format", () => {
const dateToBeChecked = '2021-12-17';
const dateFormat = (/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/.test(dateToBeChecked));
expect(dateFunction(dateToBeChecked)).toBe(dateFormat)
})

ERROR Error: InvalidPipeArgument: "12-01-2020 - 12-02-2020' to a date' for pipe 'DatePipe'

I am trying to concatenate two dates and assigning to variable but it is throwing an error
ERROR Error: InvalidPipeArgument: 'Unable to convert “12-01-2020 - 13-02-2020” into a date' for pipe 'DatePipe'.where I am going wrong?
dates which I am getting from backend is projectStartDate: "2020-12-21T13:55:00.000+00:00".I am converting it to 12-01-2020 / timestamp after that concatenating both and assigning to projectduration value.
this.startDate = this.datepipe.transform(response.projectStartDate, 'yyyy-MM-dd','es-ES');
this.endDate = this.datepipe.transform(response.projectEndDate, 'yyyy-MM-dd','es-ES');
response.gbRFEbean.projectDuration.value = this.startDate + "-" +this.endDate ;
The Date format: DD-MM-YYYY is invalid.
You can try using :
new Date("12-01-2020")
It will give Invalid Date in chrome dev tools.
Solution
You can change the date format to MM-DD-YYYY and then pass it to datepipe.transform
let date = response.projectStartDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2-$1-$3")
this.startDate = this.datepipe.transform(date, 'yyyy-MM-dd','es-ES');
date = response.projectEndDate.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2-$1-$3")
this.endDate = this.datepipe.transform(date , 'yyyy-MM-dd','es-ES');
locale is the fourth argument of the DatePipe transform and timezone is the third argument. Currently you have the locale as the third argument. I'd probably configure your locale like this (and the date pipe will automatically work for your locale without specifying):
Missing locale data for the locale "XXX" with angular
transform takes either a javascript date or an ISO date string so I'm guessing your dates (projectStartDate, projectEndDate) are strings that aren't in the ISO format? The error message implies that one of those fields has the entire value of 12-01-2020 - 13-02-2020
sample code with ISO date string
startDate = '2020-01-12';
endDate = '2020-02-13';
formattedStartDate = this.datePipe.transform(this.startDate);
formattedEndDate = this.datePipe.transform(this.endDate);
constructor(private datePipe: DatePipe) {
console.log(`${this.formattedStartDate} - ${this.formattedEndDate}`);
}
Sample code with javascript date
startDate = new Date('2020-01-12');
endDate = new Date('2020-02-13');
formattedStartDate = this.datePipe.transform(this.startDate, 'yyyy-MM-dd');
formattedEndDate = this.datePipe.transform(this.endDate, 'yyyy-MM-dd');
constructor(private datePipe: DatePipe) {
console.log(`${this.formattedStartDate} - ${this.formattedEndDate}`);
}
If your dates are strings in a dd-MM-yyyy format, you can parse them with a library like luxon:
npm i luxon
And import
import { DateTime } from 'luxon';
And parse
startDate = DateTime.fromFormat("12-01-2020", "dd-MM-yyyy").toISODate();
As a final note it's a little funny to put the dates in an ISO date format (yyyy-MM-dd) and then format them in the same format. The pipe makes more sense, particularly with you app locale set, if you want to use formats such as mediumDate (the default) which might display 12 ene. 2020

Convert given timestamp to influxdb timestamp

My Incoming Date is in format : 15.08.2017 23:03:23.120000
Here I am using Node-Red Platform to convert msg.payload.time in Influx timestamp but I am getting this Error:
"Error: Expected numeric value for, timestamp, but got '15.08.2017 23:03:23.120000'!".
Please let me know the script for given timestamp to influxdb timestamp.
InfluxDB expects unix timestamps and msg.payload.time might be a string, hence you are getting the error.
In order to generate a timeStamp from a date, you can use the Date functionality of JS.
It works in the following way:
new Date('<your-date-string>').valueOf()
Here the date-string is expected in 'YYYY-MM-DD hh:mm:ssZ' format.
In your case, since the msg.payload.time is available in dd.mm.yy hh:mm:ssZ format, you will need to perform some additional operations.
You can update your code as below:
const incomingDate = msg.payload.time;
// extract the date dd.mm.yyyy from the incoming Date String
const splittedDate = incomingDate.split(' ');
// Convert the date from dd.mm.yyyy to yyyy-mm-dd format
let date = splittedDate[0].split('.').reverse().join('-');
// Store time value in a separate variable for later use.
const time = splittedDate[1];
// merge date and time to form yyyy-mm-dd hh:mm:ssZ format
const datetime = `${date} ${time}`
// assign the timestamp value to fields.time
fields.time = new Date(datetime).valueOf();
Here is a working example
const incomingDate = '15.08.2017 23:03:23.120000';
const splittedDate = incomingDate.split(' ');
let date = splittedDate[0].split('.').reverse().join('-');
const time = splittedDate[1];
const datetime = `${date} ${time}`
console.log(datetime);
console.log(new Date(datetime).valueOf())

JSON Field with date format using Javascript?

As of now I can get the json format of my data using this code
var bookingReserve = ['{!! $booking !!}'];
var json = JSON.parse(bookingReserve);
console.log(json);
and output like this
What I need to do is to generate json format based on the data thrown by bookingReserve
and
set date format Y-m-d to starts_at and ends_at
Unfortunately I can't filter the date format of the fields using laravel as I ask here
Convert DATE_FORMAT to Y-m-d? Using Larave Eloquent Raw Select
So what I'm trying to do is to generate json format and set Y-m-d date format for both fields using javascript
const formatDate = dateString => {
const d = new Date(dateString)
return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`
}
formatted = json.map(obj => {
return {
starts_at: formatDate(obj.starts_at),
ends_at: formatDate(obj.ends_at)
}
})
Or with your case, just need to trim after space.
formatted = json.map(obj => {
return {
starts_at: obj.starts_at.split(" ")[0],
ends_at: obj.ends_at.split(" ")[0]
}
})

Categories

Resources