首页 > 解决方案 > 将 mysql 表中的日期字符串转换为特定格式

问题描述

在下面的示例中,我需要20-Jan-2021在里面inpdate
将一个字符串 -2021-01-20从服务器端给出 - 转换为相应的格式
有什么帮助吗?

let a = "2021-01-20";  // given from mysql table
let b = ???;
$('#inpdate').val(b);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='inpdate'>

标签: javascriptjquery

解决方案


您可以从此处给出的日期创建一个新的 Date 对象,然后访问其属性以构建您喜欢的字符串:

function reformatDate(dateString) {
  const dateObject = new Date(dateString);
  return `${dateObject.getDate()}-${dateObject.toLocaleString('default', { month: 'short' })}-${dateObject.getFullYear()}`;
}

console.log(reformatDate('1970-01-01'));
console.log(reformatDate('2021-01-20'));


推荐阅读