繁体   English   中英

Jquery 新日期 - 转换为 yyyy-MM-dd 并使用 toLocaleDateString

[英]Jquery new Date - Convert to yyyy-MM-dd and use toLocaleDateString

我有一个 HTML 输入框设置为 type=date

<input name="datereceived" type="date" class="FormDateValues" id="datereceived" />

我想在文档加载到今天的日期时使用 Jquery 填充此输入框,但因为我在澳大利亚,我必须使用 GMT+10 进行偏移

为了获得日期,我执行以下操作:

var newDate = new Date();

然后我尝试使用以下方法设置输入框:

$('#datereceived').val(newDate.toLocaleDateString());

浏览器告诉我,对于 type=date,格式必须设置为 yyyy-MM-dd 而不是 dd/MM/yyyy 的澳大利亚时间格式。

我不确定如何执行 toLocaleDateString 并将日期转换为 yyyy-MM-dd。

尝试使用fr-CA返回yyyy-MM-dd格式。

 var yyyymmdd = (new Date ()).toLocaleDateString ("fr-CA"); console.log (yyyymmdd);

如果您需要本地日期(在您的情况下为 GMT+10),则需要使用Date方法:

function toHtmlDate (d) {
  return (d.getFullYear() + '-0' + (d.getMonth() + 1) + '-0' + d.getDate()).replace(/-0(\d\d)/g, '-$1');
}

如果您需要 ISO 日期 (GMT),您可以使用new Date().toISOString().substring(0, 10) 解释:

  • Date.prototype.toLocaleDateString输出取决于您的语言环境,对它使用字符串拆分可能不适用于其他用户
  • Date.prototype.toISOString总是返回####-##-##T##:##:##.###<timezone> ,例如2015-10-18T23:23:22.880Z 取前 10 个字符,您有<year>-<month>-<date>

尝试使用String.prototype.split() , Array.prototype.splice() , Array.prototype.join()

 // create array of values returned by `.toLocaleDateString()`, // delimited by `/` var d = new Date().toLocaleDateString().split("/"); // `y` : year var y = d.splice(-1)[0]; // set `y` as item at index `0` of `d` d.splice(0, 0, y); // join items within `d` with dash character `"-"` var date = d.join("-"); console.log(date);

除了提到的解决方案:

如果您加载了 jQuery UI:

// jQuery UI datepicker
$.datepicker.formatDate("yy-mm-dd", new Date())

如果你有 Moment.JS

// Moment JS
moment().format("YYYY-MM-DD")

如果您需要其他工具来解析、格式化、匹配日期或在时区之间转换它们,我建议您查看Moment.js库。

使用toISOStringslice

 var today = new Date().toISOString().slice(0, 10) console.log(today)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM