Ric*_*rdo 410 javascript string time date concatenation
我有一个脚本,用JavaScript打印当前的日期和时间,但DATE总是错的.这是代码:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Run Code Online (Sandbox Code Playgroud)
它应该打印18/04/2012 15:07:33和打印3/3/2012 15:07:33
有帮助吗?谢谢
Mar*_*ers 551
通话时,.getMonth()您需要添加+1才能显示正确的月份.Javascript计数总是从0开始(看这里检查原因),所以调用.getMonth()可能会返回4而不是5.
因此,在您的代码中,我们可以使用currentdate.getMonth()+1输出正确的值.此外:
.getDate()返回月中的某天< - 这是您想要的那一天.getDay()是Date对象的一个单独方法,它将返回一个表示当前星期几(0-6)0 == Sunday等的整数所以你的代码应该是这样的:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
Run Code Online (Sandbox Code Playgroud)
JavaScript Date实例继承自Date.prototype.您可以修改构造函数的原型对象,以影响JavaScript Date实例继承的属性和方法
您可以使用Date原型对象来创建一个新方法,该方法将返回今天的日期和时间.这些新方法或属性将由Date对象的所有实例继承,因此如果您需要重新使用此功能,它将特别有用.
// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过执行以下操作来简单地检索日期和时间:
var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();
Run Code Online (Sandbox Code Playgroud)
或者调用内联方法,这样就可以了 -
var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();
Run Code Online (Sandbox Code Playgroud)
Chh*_*lit 242
要获得时间和日期,你应该使用
new Date().toLocaleString();
>> "09/08/2014, 2:35:56 AM"
Run Code Online (Sandbox Code Playgroud)
只获得您应该使用的日期
new Date().toLocaleDateString();
>> "09/08/2014"
Run Code Online (Sandbox Code Playgroud)
只获得你应该使用的时间
new Date().toLocaleTimeString();
>> "2:35:56 AM"
Run Code Online (Sandbox Code Playgroud)
或者,如果你只想要hh:mm没有AM/PM 格式的美国英语时间
new Date().toLocaleTimeString('en-US', { hour12: false,
hour: "numeric",
minute: "numeric"});
>> "02:35"
Run Code Online (Sandbox Code Playgroud)
或英国英语
new Date().toLocaleTimeString('en-GB', { hour: "numeric",
minute: "numeric"});
>> "02:35"
Run Code Online (Sandbox Code Playgroud)
在这里阅读更多.
Dan*_*Lee 63
对于这个真正的mysql样式,请使用以下函数: 2019/02/28 15:33:12
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);Run Code Online (Sandbox Code Playgroud)
<div id="digital-clock"></div>Run Code Online (Sandbox Code Playgroud)
Ste*_*eve 27
只需使用:
var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");
Run Code Online (Sandbox Code Playgroud)
Kam*_*ski 13
我开发了史蒂夫的答案,以获得 OP 所需要的
new Date().toLocaleString().replace(',','')
Run Code Online (Sandbox Code Playgroud)
new Date().toLocaleString().replace(',','')
Run Code Online (Sandbox Code Playgroud)
Chu*_*ris 11
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+(currentdate.getMonth()+1)
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Run Code Online (Sandbox Code Playgroud)
将.getDay()方法更改为.GetDate()并添加一个月,因为它从0开始计算月数.
通过使用默认值Date()
const now = new Date();
console.log(now); // Output: Thu Sep 23 2021 13:24:52 GMT-0400 (Eastern Daylight Time)
Run Code Online (Sandbox Code Playgroud)
对于不同的日期和时间格式,您可以使用toLocaleString():
MM/DD/YYYY
const now = new Date();
const formattedDate = now.toLocaleString('en-US', { dateStyle: 'short' });
console.log(formattedDate);
// Output: "9/23/2021"
Run Code Online (Sandbox Code Playgroud)
Weekday, Month Day, Year
const now = new Date();
const formattedDate = now.toLocaleString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });
console.log(formattedDate);
// Output: "Thursday, September 23, 2021"
Run Code Online (Sandbox Code Playgroud)
HH:MM AM/PM
const now = new Date();
const formattedDate = now.toLocaleString('en-US', { timeStyle: 'short' });
console.log(formattedDate);
// Output: "1:24 PM"
Run Code Online (Sandbox Code Playgroud)
HH:MM:SS AM/PM Timezone
const now = new Date();
const formattedDate = now.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true, timeZoneName: 'short' });
console.log(formattedDate);
// Output: "1:24:52 PM EDT"
Run Code Online (Sandbox Code Playgroud)
YYYY-MM-DDTHH:MM:SSZ
const now = new Date();
const isoDate = now.toISOString();
console.log(isoDate);
// Output: "2021-09-23T17:24:52.740Z"
Run Code Online (Sandbox Code Playgroud)
小智 6
基本 JS(很好学习):我们使用 Date() 函数并执行我们需要的所有操作,以我们的自定义格式显示日期和日期。
var myDate = new Date();
let daysList = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let monthsList = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Aug', 'Oct', 'Nov', 'Dec'];
let date = myDate.getDate();
let month = monthsList[myDate.getMonth()];
let year = myDate.getFullYear();
let day = daysList[myDate.getDay()];
let today = `${date} ${month} ${year}, ${day}`;
let amOrPm;
let twelveHours = function (){
if(myDate.getHours() > 12)
{
amOrPm = 'PM';
let twentyFourHourTime = myDate.getHours();
let conversion = twentyFourHourTime - 12;
return `${conversion}`
}else {
amOrPm = 'AM';
return `${myDate.getHours()}`}
};
let hours = twelveHours();
let minutes = myDate.getMinutes();
let currentTime = `${hours}:${minutes} ${amOrPm}`;
console.log(today + ' ' + currentTime);Run Code Online (Sandbox Code Playgroud)
Node JS(快速简便):使用(npm install date-and-time)安装 npm pagckage ,然后运行以下命令。
let nodeDate = require('date-and-time');
let now = nodeDate.format(new Date(), 'DD-MMMM-YYYY, hh:mm:ss a');
console.log(now);
Run Code Online (Sandbox Code Playgroud)
getDay()获取星期几。 3是星期三。你想要的getDate(),那就会回来18。
同样getMonth()从 开始0,您需要添加1以获取4(四月)。
演示: http: //jsfiddle.net/4zVxp/
这应该做的伎俩:
function dateToString(date) {
var month = date.getMonth() + 1;
var day = date.getDate();
var dateOfString = (("" + day).length < 2 ? "0" : "") + day + "/";
dateOfString += (("" + month).length < 2 ? "0" : "") + month + "/";
dateOfString += date.getFullYear();
return dateOfString;
}
var currentdate = new Date();
var datetime = "Last Sync: ";
datetime += dateToString(currentdate );
datetime += + currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
Run Code Online (Sandbox Code Playgroud)
您需要使用 getDate() 来获取日期部分。getDay() 函数返回天数(星期日 = 0、星期一 = 1...),而 getMonth() 返回基于 0 的索引,因此您需要将其加 1。
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+ (parseInt(currentdate.getMonth()) + 1)
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Run Code Online (Sandbox Code Playgroud)
小智 5
我从这里找到了在 JavaScript 中获取当前日期和时间的最简单方法 - How to get current Date and Time using JavaScript
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var CurrentDateTime = date+' '+time;
Run Code Online (Sandbox Code Playgroud)
小智 5
const date = new Date()
console.log(date.toLocaleTimeString("en-us", {timeStyle: "medium"})) // Only Time
console.log(date.toLocaleString()) // For both Date and Time
Run Code Online (Sandbox Code Playgroud)