“`javascript 将 “dd/MM/yyyy hh:mm tt” 转换为 “yyyy-mm-ddThh:mm” 在Javascript中 “`

huangapple go评论61阅读模式
英文:

Convert "dd/MM/yyyy hh:mm tt" To "yyyy-mm-ddThh:mm" In Javascript

问题

"Invalid Date" showing as It's but Date Invalid "25/05/2023 2:30 PM" new Date console.log

英文:

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:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

But It's showing as "Invalid Date"

答案1

得分: 2

你可以提取日期部分并手动构建日期字符串,如下所示:

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')
  
  // 提取日期部分
  const parts = match.slice(1);
  let day     = parts[0]; 
  let month   = parts[1];
  let year    = parts[2];
  let hours   = parseInt(parts[3], 10); // 必须转成整数,以便于为24小时制加12
  let minutes = parts[4];
  
  // 将12小时制转成24小时制
  hours += (parts[5] == 'PM' ? 12 : 0);
  
  // 将小时补齐成两位数
  hours = ('00'+hours).substr(-2);
  
  // 以任何你喜欢的格式返回日期字符串
  return `${year}-${month}-${day}T${hours}:${minutes}`; 
}

遗憾的是,JavaScript 不支持在正则表达式中使用 /x 标志或自定义分隔符,就像 Perl 那样。因此,正则表达式看起来有点拥挤,但基本上很简单明了。

英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

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(&#39;Invalid date format&#39;)
  
  // 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] == &#39;PM&#39; ? 12 : 0);
  
  // pad hours to two digits
  hours = (&#39;00&#39;+hours).substr(-2);
  
  // format any way you like: 
  return `${year}-${month}-${day}T${hours}:${minutes}`; 
}

<!-- end snippet -->

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.

答案2

得分: 1

相对简单的解析时间戳,获取数值并按要求重新格式化,将小时转换为24小时制,例如:

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

// 获取数值
let [day, month, year, hour, min, ap] = timestamp.match(/\w+/g);

// 将小时转换为24小时制
hour = (/am/i).test(ap)? hour : +hour + 12;

// 将小时填充为2位数字
hour = ('0' + hour).slice(-2);

// 格式化为所需格式
console.log(`${year}-${month}-${day}T${hour}:${min}`);

在途中添加一些验证和检查以避免错误,如果时间戳不能保证符合OP格式。

英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

// 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 = (&#39;0&#39; + hour).slice(-2);

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

<!-- end snippet -->

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

答案3

得分: -1

你可以拆分日期并按所需格式组合它。一旦你得到了格式,你可以将字符串传递给日期对象,然后在应用程序中随意使用该日期。
以下是一个示例:

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

// 如果你需要去除分钟后的部分
const finalDate = parsedISODate.toString().substring(0, parsedISODate.toString().lastIndexOf(':'));
console.log(finalDate);

以上是代码示例。

英文:

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.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

// If you need to remove last part after minutes
const finalDate = parsedISODate.toString().substring(0, parsedISODate.toString().lastIndexOf(&#39;:&#39;));
console.log(finalDate);

<!-- end snippet -->

答案4

得分: -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);

英文:

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 :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

// 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 === &quot;PM&quot; &amp;&amp; hour &lt; 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 &quot;yyyy-mm-ddThh:mm&quot;
var formattedDate = date.toISOString().slice(0, 16);

console.log(formattedDate);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月26日 15:21:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定