1

I have date in "dd/MM/yyyy hh:mm tt" format eg. (25/05/2023 2:30 PM).

And I want to convert it into "yyyy-mm-ddThh:mm" this format eg. (2023-05-25T14:30) by using Javascript.

I tried like this:

console.log(new Date("25/05/2023 2:30 PM"));

But It's showing as "Invalid Date"

kevinSpaceyIsKeyserSöze
  • 3,693
  • 2
  • 16
  • 25

4 Answers4

2

You could extract the date parts and build the date string manually, like so:

const mydate = "25/05/2023 2:30 PM";

console.log( dateFormatter(mydate) );

function dateFormatter(datestr){
  const regex = /^(\d{2})\/(\d{2})\/(\d{4}) (\d{1,2}):(\d{2}) ([AP]M)$/;
  const match = datestr.match(regex);

  if( ! match )
    throw new Error('Invalid date format')
  
  // pull out the date parts
  const parts = match.slice(1);
  let day     = parts[0]; 
  let month   = parts[1];
  let year    = parts[2];
  let hours   = parseInt(parts[3], 10); // must be int to add 12 for 24H
  let minutes = parts[4];
  
  // change 12H to 24H
  hours += (parts[5] == 'PM' ? 12 : 0);
  
  // pad hours to two digits
  hours = ('00'+hours).substr(-2);
  
  // format any way you like: 
  return `${year}-${month}-${day}T${hours}:${minutes}`; 
}

Javascript sadly does not support the /x flag or custom delimiters in regexes, like Perl does. So the regex is a little crammed and suffers from leaning toothpicks.

Otherwise, it is pretty straight forward.

Levi
  • 661
  • 7
  • 26
  • 1
    You've over complicated the parsing part. Consider `let [day, month, year, hour, min, ap] = timestamp.match(/\w+/g)`. ;-) – RobG May 26 '23 at 10:18
  • I like that! :) but that would also successfully parse many things that are not dates. – Levi Jun 14 '23 at 08:14
  • 1
    It just gets the values, validation is another step (and [not too difficult](https://stackoverflow.com/a/5812341/257182)). ;-) – RobG Jun 14 '23 at 09:01
  • Yeah, separating extraction and validation is probably a good idea, especially for readability. – Levi Jun 14 '23 at 09:08
1

Fairly simple to parse the timestamp to get the values and reformat as required after converting the hour to 24 hour clock, e.g.

let timestamp = "25/05/2023 2:30 PM";

// Get the values
let [day, month, year, hour, min, ap] = timestamp.match(/\w+/g);

// Convert hour to 24 hour
hour = (/am/i).test(ap)? hour : +hour + 12;

// Pad hour to 2 digits
hour = ('0' + hour).slice(-2);

// Format as required
console.log(`${year}-${month}-${day}T${hour}:${min}`);

You should add some validation and checking along the way to avoid errors if the timestamp isn't guaranteed to meet the OP format.

RobG
  • 142,382
  • 31
  • 172
  • 209
-1

You can split the date and combine it in required format. Once you get the format you can pass the string to date object and you can then use that date however you like in your application. Here is one such example.

const initialDate = "25/05/2023 2:30 PM";
const dateParts = initialDate.split(' ');
const timeComp = dateParts[1] + " " + dateParts[2];
const dateSplit = dateParts[0].split(/\//);
const dateComp = [dateSplit[2], dateSplit[1], dateSplit[0]].join('-') + " " + timeComp;
const parsedISODate = new Date(new Date(dateComp).toString().split('GMT')[0] + ' UTC').toISOString();
console.log(parsedISODate);

// If you need to remove last part after minutes
const finalDate = parsedISODate.toString().substring(0, parsedISODate.toString().lastIndexOf(':'));
console.log(finalDate);
CodeThing
  • 2,580
  • 2
  • 12
  • 25
-1

The resulting formattedDate will be in the desired "yyyy-mm-ddThh:mm" format, which in this example will be "2023-05-25T14:30".

Try below Code :

// Input date string in "dd/MM/yyyy hh:mm tt" format
var inputDateStr = "25/05/2023 2:30 PM";

// Split the input date string into its components
var dateComponents = inputDateStr.split(/[/ :]/);

// Extract the day, month, year, hour, and minute components
var day = dateComponents[0];
var month = dateComponents[1] - 1; // Month is zero-based in JavaScript Date object
var year = dateComponents[2];
var hour = dateComponents[3];
var minute = dateComponents[4];
var period = dateComponents[5]; // AM or PM

// Adjust the hour based on the period (AM/PM)
if (period === "PM" && hour < 12) {
  hour = parseInt(hour, 10) + 12;
}

// Create a new Date object using the extracted components
var date = new Date(year, month, day, hour, minute);

// Format the date as "yyyy-mm-ddThh:mm"
var formattedDate = date.toISOString().slice(0, 16);

console.log(formattedDate);
Mahesh Thorat
  • 1
  • 4
  • 11
  • 22
  • This produces `2023-05-2512:30`, missing a `T` and hour is 12 instead of 14 – Levi May 26 '23 at 09:23
  • I get 2023-05-2504:30. Having parsed the timestamp to get the values, just format them as a string and return that. No need for a *Date* at all. Note that the values passed to the *Date* constructor are treated as local, but the output string is UTC so will show a different time and possibly date depending on the user's system offset. – RobG May 26 '23 at 10:11
  • @Levi I have modified code – Mahesh Thorat May 26 '23 at 10:29
  • @RobG now will you get `2023-05-25T09:00` – Mahesh Thorat May 26 '23 at 10:30
  • I still get the same result. The time should be 14:30 regardless of user timezone. My previous comment tells you why the result is wrong for users with a non–zero offset. – RobG May 26 '23 at 10:38