Home > Back-end >  regex convert text to date
regex convert text to date

Time:12-17

I'm using parsehub to extract data and there is a date in the format thursday 22 december 2022
but I need it in a date string dd/mm/yyyy is there a way to do that with regex javascript?

I can't find info about a way to solve this

CodePudding user response:

You could solve it without regex using only JavaScript

1: Parse your string into a date

2:Extract and concatenate needed values using JS built-in date methods

function formatDate(date) {
    let parsed = new Date(date);
    return `${parsed.getDate()}/${parsed.getMonth()   1}/${parsed.getFullYear()}`;
}
console.log(formatDate('Thursday 22 december 2022'));

CodePudding user response:

You can do it without regex as well

function myDateFormat(date) {
    var d = new Date(date),
        month = ''   (d.getMonth()   1),
        day = ''   d.getDate(),
        year = d.getFullYear();

    return [day, month, year].join('/');
}
 
console.log(myDateFormat('Thursday 22 december 2022'));

The above will not add '0' to the month and date so you need to add a condition to get the date and month as 'dd' and 'mm' instead of d and m.

if (month.length < 2) 
    month = '0'   month;
if (day.length < 2) 
    day = '0'   day;

CodePudding user response:

Simply :
please note the addition of zeros on months, days when these are less than 10

const strDate2dmy = dteStr => new Date(dteStr).toLocaleDateString('fr-FR');
 

console.log( strDate2dmy( 'Thursday 22 december 2022' ) )  // 22/12/2022
console.log( strDate2dmy( 'Monday 4 July 2022' ) )         // 04/07/2022

  • Related