Date-fns is being received as null value on the backend - javascript

Frontend: React
Backend: SpringBoot
Date format on the BE: 2011-10-05T14:48:00.000Z
I've tried to use the date-fns to send the correct format from the FE to the BE application, ut even following the documentation, the BE is receiving null.
Salvar = async () => {
const {update} = this.state;
const {dtInclusao} = this.state.compra.dtInclusao
var result = parse(
dtInclusao,
"dd/mm/yyyy",
new Date()
)
const response = await api.post('SolicCompra/compra',
{...this.state.compra, dtInclusao: result}, {'Content-type':
'application/json'});
The expected format is dd/MM/yyyy.

Here are some date-fns helpers I use on a regular basis:
export const parseDate = dateString => {
return Date.parse(dateString.replace(/-/g, '/').replace('T', ' '))
}
export const formatDate = date => {
return format(date, 'dd/MM/yyyy')
}
The first will parse date and timestamps into a Date object. The second will take that date object and format it back to a string in the format you want.
Using these helper functions you can update your code to:
var result = formatDate(parseDate(dtInclusao))

Related

Extract datetime from string with javascript

I have an AJAX request that returns an array, in this array I capture the created_at from my database and it comes in the following format:
Code:
success: function(response){
let data = response;
date = data[0][`created_at`];
console.log(date);
}
log:
2022-08-25T18:44:48.000000Z
I need to split this string into two variables (date and time), what is the best way?
you can do it like this,
success: function(response){
let data = response;
date = data[0][`created_at`];
// date.split('T') - this will create an array like ['2022-08-25', '18:44:48.000000Z']
// const [date, time] - this is Array destructuring in action.
const [date, time] = date.split('T')
// date - '2022-08-25'
// time - '18:44:48.000000Z'
console.log(date, time)
}
checkout this: What does this format mean T00:00:00.000Z?
also checkout: Destructuring assignment
Let date = new Date(data[0][`created_at`]);
Console.log(date.format('dd/mm/yy'))
Try to install moment.js

Use date-fns to format day as UTC

I have the following date format 2022-07-20 and I would like to parse into the following format 2022-07-20T00:00:00.000Z
I'm using the following code
const main = () => {
const day = '2022-07-20'
const date = new Date()
const result = parse(day.toString(), 'yyyy-MM-dd', date)
console.log(result.toISOString())
}
And getting the following output 2022-07-19T21:00:00.000Z. I assume this happening because my timezone is UTC+3.
How do I get it formatted as 2022-07-20T00:00:00.000Z?

Comparing two date values in cypress

I'm trying to check if one date value that I get from the element in the app is less than today's date:
const todaysDate = Cypress.moment().format('DD/MM/YYYY')
it("Check date to be less or equal than todays", () => {
cy.get('.date', { timeout: 15000 }).eq(3).invoke('text').should('be.lte', todaysDate);
})
However I'm getting the following error:
Timed out retrying after 4000ms: expected '12/14/2020' to be a number or a date
Is there a way to convert the date I get from element to a datetime object?
You can use what JavaScript has to offer:
const date = new Date('12/14/2020');
so in the context of Cypress:
it("Check date to be less or equal than today", () => {
cy
.get('.date', { timeout: 15000 })
.invoke('text')
.then(dateText => {
const date = new Date(dateText);
const today = new Date();
expect(date).to.be.lte(today);
});
});
The moment library is deprecated, using dayjs is recommended instead. You'll need this when parsing custom date formats, which might not be supported by the Javascript Date constructor. Based upon your error message I assume the expected format should be MM/DD/YYYY instead of DD/MM/YYY.
it("Check date to be less or equal than todays", () => {
cy.get('.date', { timeout: 15000 }).invoke('text').then(actualDateText => {
const dayjs = require('dayjs');
const todaysDate = new Date();
const actualDate = dayjs(actualDateText, 'MM/DD/YYYY').toDate();
expect(actualDate).to.be.lte(todaysDate);
});
});

Problem with changing string to date with time

Date format looks like that: 2020-07-11 23:11:52
I am taking data from csv file using fetch and splitting it into single data
How to change this string (date) into date with time to plot on the chart
async function getData(){
const response =await fetch('data.csv');
const data = await response.text();
const table = data.split('\n').slice(1);
table.forEach(row =>{
const columns = row.split(',');
const date = columns[0];
// const dayshours = date.split(' ');
// const days = dayshours[0];
xlabels.push(date);
const temp = columns[1];
ytemps.push(temp);
console.log(date, temp);
});
}
Map the numbers into a string in the ISO standard, which looks like '2020-08-10T22:36:25.772'
So in your case it would look like '2020-07-11T23:11:52.000'. Note that it looks pretty much identical to what you've already got, except the T between the date and the time of day, and append .000 to the end to set the milliseconds component to zero.
Then take your string and use new Date('2020-07-11T23:11:52.000')

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