skip to Main Content

I’m using Moment.js to parse the Date from a string, however every time I parse it I have to specify the format the string is in, but my string can either be dd-MM-yy or d/m/yyyy or d-MM-yyyy, its always changing, so writing out all the different formats will be challenging, is there a way to parse it if I know the string will always be the day followed by the month followed by the year? Either with JavaScripts date constructor or a third party library like Moment.js

3

Answers


  1. Can you share your code, I didnt exactly get it but while I was using moment.js
    and I had date of any kind , we can format is by using

    moment(your_date).format('D-MM-YYYY') or  moment(your_date).format('D/MM/YYYY');
    

    If that clears your doubt then well and good otherwise let me know what have you sent and what exactly is required in code. Thanks

    Login or Signup to reply.
  2. read this example code

    const dateString = "05-05-2023"; // example date string in "day-month-year" format
    
    const parts = dateString.split(/[-/]/); // split the string into parts using either "-" or "/" as the delimiter
    
    const year = parts[2];
    const month = parseInt(parts[1]) - 1; // subtract 1 from the month because it is zero-indexed in the Date() constructor
    const day = parts[0];
    
    const date = new Date(year, month, day);
    
    console.log(date); // Fri May 05 2023 00:00:00 GMT+0000 (Coordinated Universal Time)
    
    Login or Signup to reply.
  3. Simply match for numbers (i.e. days, month, year), then use the Date() constructor:

    function parseDate(dateString) {
      const [days, month, year] = dateString.match(/d+/g);
      const monthIndex = month - 1;
    
      return new Date(year, monthIndex, days);
    }
    
    console.log(parseDate("2-5-23"));
    console.log(parseDate("02-05-2023"));
    console.log(parseDate("02/05/2023"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search