JSON Field with date format using Javascript? - 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]
}
})

Related

formatting date into ISO string for `react-admin`

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.

Unable to convert data '19-10-2002' into date

I need to pass a date parameter in format (dd-MM-yyyy) and convert in this format (yyyy-MM-dd) to send API.
So I do this:
convert(date:string){
date //is in the format(dd-MM-yyyy)
date =formatDate(date , "yyyy-MM-dd", 'en_US');
and I obtain this error:
Unable to convert "19-10-2002" into a date
Anyone can help me?
You could just do
console.log(
"19-10-2002".split('-').reverse().join('-')
)
If you want to pass a string to "formatDate" it has to be in "ISO date-time" format (the complete format is "YYYY-MM-DDThh:mm:ss.sTZD", but you can drop any part from the end and use like "YYYY" or "YYYY-MM-DD"). so the string you are passing to it is not recognized as a valid input date.
so you can use Dave's code
Here is the custom date formatter function which accepts date, format and separator/delimiter to convert the passed date with passed format.
function dateFormatter(date, format, delimiter) {
const dateItems = date.split(delimiter)
const formatItems = format.toLowerCase().split(delimiter);
const day = formatItems.indexOf('dd');
const month = formatItems.indexOf('mm');
const year = formatItems.indexOf('yyyy');
const formattedDate = ([dateItems[day], dateItems[month], dateItems[year]]).join(delimiter)
console.log(formattedDate)
return formattedDate
}
// run example
dateFormatter('02-03-2020', 'YYYY-MM-DD', '-');
dateFormatter('02/03/2020', 'MM/DD/YYYY', '/');

From date to date validation using javascript

I want to validate from and to date. my date format is d/m/Y H:i
Here is my code:
var startDate = new Date($('#fromdate').val());
var endDate = new Date($('#todate').val());
if (endDate.getTime() <= startDate.getTime()) {
return [false,"To Date cannot be less than From Date"];
}else{
return [true,""];
}
result showing 'Invalid Date'.
Here the date format is different. How to change the date format before passing to Date function?.
You can parse the date string on your own or you can use an external library, like dayjs or momentjs
A simple parsing function could be something like this (assuming the format is the one you mentioned in your question):
function getDateFromCustomFormat(dateString) {
const dateFormatPattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})$/
const parts = dateString.match(dateFormatPattern)
console.log(parts)
const validFormatString = `${parts[3]}-${parts[2]}-${parts[1]} ${parts[4]}:${parts[5]}`
new Date(validFormatString)
}

How to create date from a specified format in JavaScript similar to DateTime::createFromFormat

I expect to get a date from my database in Ymd format.
This gives me values like 20200202. This is fine for php applications but I'm using JavaScript for the frontend.
In php, we could do something like
$date = DateTime::createFromFormat('Ymd', '20200202');
meaning I get a date object as long as the formats match.
Is there a way for JavaScript to do this?
If you are sure this date will always come in the format yyyymmdd, you can use RegEx to extract the date :
function getDate(inputDate)
{
// TODO : Check if the format is valid
const pattern = /(\d{4})(\d{2})(\d{2})/
const parts = inputDate.match(pattern);
// months start with 0 in js, that's why you need to substract 1
// -----------------------v----------v
return new Date(parts[1], parts[2] - 1, parts[3]);
}
console.log(getDate("20200202").toString());
console.log(getDate("20200213").toString());
console.log(getDate("20201231").toString());
You could always check if the format matches your requirements and then split the value you get from the database. Then you could either return a Boolean value false if not possible or a date.
const dbOutput = '20200202';
const createdDate = getDate(dbOutput);
function getDate(value) {
if(value.length !== 8) {
return false;
}
const year = +value.substring(0,4);
const month = +value.substring(4,6);
const day = +value.substring(6,8);
try {
return new Date(year, month-1, day);
} catch (error) {
return false;
}
}

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

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

Categories

Resources