将2018年8月19日转换为2018年8月19日-Javascript

时间:2018-06-28 04:24:21

标签: javascript

我想将日期为“ Aug 19th 2018”的字符串转换为“ mm-dd-yyyy”格式(不使用moment.js)  我用过

d = new Date("Aug 19th 2018")

由于无法解析“ 19th”,因此导致NaN。如何实现呢?

6 个答案:

答案 0 :(得分:2)

创建自定义函数并将日期转换为所需格式

let dt = "Aug 19th 2018";


function convertDate(dt) {
  let newFormat = "";
  // a mapping of month name and numerical value
  let monthMapping = {
    jan:'01',
    feb: '02',
    mar: '03',
    april: '04',
    may: '05',
    june: '06',
    july: '07',
    aug: '08',
    sept: '09',
    oct: '10',
    nov: '11',
    dec: '12'
  }
  // split the input string into three pieces
  let splitDt = dt.split(" ");
  // from the first piece get the numerical month value from the above obhect
  let getMonth = monthMapping[splitDt[0].toLowerCase()];
  let date = parseInt(splitDt[1], 10)
  let year = splitDt[2]
  return `${getMonth}-${date}-${year}`
}

console.log(convertDate(dt))

答案 1 :(得分:2)

您可以split()字符串,使用对象获取月份索引,并使用parseInt()从日期中提取数字。

使用new Date(year, monthIndex , day)获取日期对象。

let formatDate = s => {
  let months = {jan:'0',feb:'1',mar:'2',apr:'3', may:'4',jun:'5',jul:'6',aug:'7',sep:'8',oct:'9',nov:'10',dec:'11'};
  let [m, d, y] = s.split(' ');
  return new Date(y, months[m.toLowerCase()], parseInt(d));
};

var date1 = formatDate("Aug 19th 2018");
var date2 = formatDate("Mar 19th 2000");

文档:new Date()

答案 2 :(得分:2)

您可以使用正则表达式替换日期值中的所有字母,然后将字符串再次传递给Date()构造函数

var dateString = "AUG 19th 2018";
var dateFrag = dateString.split(' ');
dateFrag[1] = dateFrag[1].replace(/[a-zA-Z]/g,'');
var d = new Date(dateFrag);
console.log(d);

答案 3 :(得分:1)

更新,您可以先替换该“ th”,“ rd”

var mydate= new Date(ReturnProperDate("Aug 19th 2018"));

//you can create manual function to handle format now
console.log( (1+mydate.getMonth()) +"-"+ mydate.getDate()+"-" + mydate.getFullYear());

function ReturnProperDate(date){

  date=date.replace('th','');
  date=date.replace('rd','');
  date=date.replace('xx',''); //if any other
  
  return date;
  

}

使用时刻js:https://momentjs.com/

那么您就可以轻松地将自己的约会对象变成伴侣

 moment(yourDate).format('DD-MMM-YYYY'); // put format as you want 

 moment().format('MMMM Do YYYY, h:mm:ss a'); // June 28th 2018, 9:58:10 am

答案 4 :(得分:1)

@Saurin Vala的解决方案存在一个问题,正如js doc所说的那样,当解析字符串时,必须给出一种格式,否则它将构造js Date(),这在某些浏览器上可能无法运行take a look at the issue on moment js doc 。 正确的方式就是这样

var a = moment("Aug 19th 2018", 'MMM Do YYYY')

date formating link

现在您可以通过多种方式输出格式

答案 5 :(得分:1)

尝试使用String.replace():

(function() {
  'use strict';

  angular.module('users').controller('TestownerControllerController', TestownerControllerController);

  TestownerControllerController.$inject = ['$scope'];

  function TestownerControllerController($scope) {
    var vm = this;

    // Testowner controller controller logic
    // ...

    init();

    function init() {
    }
  }
})();

相关问题