函数 getUTCDate() returns 一个月

Function getUTCDate() returns a month

我有代码(19是日,6是月)

var dateObj = new Date("19.6.2018");
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

newdate =  day + '.' + month + '.' + year;
alert(newdate);

此代码returnsNaN.NaN.NaN

函数 getUTCDate() returns 一个月。不知道为什么。

我是斯洛伐克人。第一个数字是日期。第二个数字是一个月。

Date 的 dateString 参数必须采用 Date.parse()

可识别的格式

String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

日期时间字符串可能采用简化的 ISO 8601 格式。例如,“2011-10-10”

你的情况可以是

var dateObj = new Date("2018-06-19");
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

newdate =  day + '.' + month + '.' + year;
console.log(newdate);

你可以像

一样使用你的字符串并正确格式化它

const str = "19.6.2018"
const arr = str.split('.');
const newString = `${arr[1]}-${arr[0]}-${arr[2]}`;
console.log(newString)
var dateObj = new Date(newString);
console.log(dateObj)
    var month = dateObj.getUTCMonth() + 1; //months from 1-12
    var day = dateObj.getUTCDate();
    var year = dateObj.getUTCFullYear();

    newdate =  day + '.' + month + '.' + year;
    alert(newdate);

除了@Shubham Khatri 的回答之外,您还可以通过以下方式将输入转换为正确的格式:

const getUTCDate = (year, month, day ) => {
  const date = new Date(`${year}-${month}-${day}`);
  const m = date.getUTCMonth() + 1; //months from 1-12
  const d = date.getUTCDate();
  const y = date.getUTCFullYear();

  return [m, d, y]
}

const input = '19.6.2018'
const date = input.split('.')
// Here we convert your input, in the correct order `getUTCDate` expected
const result = getUTCDate(date[2], date[1], date[0])
console.log(result)