将字符串转换为日期对象,添加两个小时并转换回字符串(JavaScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18663744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:48:26  来源:igfitidea点击:

Converting string to date object, adding two hours and converting back to string (JavaScript)

javascriptjquerydatetypeerror

提问by nimrod

I have a date string, want to convert it into a date object, add 2 hours and print out the converted date object back to a variable. But I get the error listed bellow:

我有一个日期字符串,想将其转换为日期对象,添加 2 小时并将转换后的日期对象打印回变量。但我得到下面列出的错误:

// dateTime: 2013-09-27 09:50:05 
var dateTime = $("#inputDatetime").val();
var startDate = dateTime;
var date = new Date(startDate);
var duration = 2;
var endDate = date;
endDate.setHours(date.getHours()+duration)
var dateString = endDate.format("dd-m-yy hh:mm:ss");

Error:

错误:

Uncaught TypeError: Object [object Date] has no method 'format'

Why do I get this TypeError?

为什么我会收到这个 TypeError?

回答by sudhan kantharuban

Vaibs, there is no method "format", you can do formating using available methods from Date Object. please don't use plugin

Vaibs,没有“格式化”方法,您可以使用 Date Object 中的可用方法进行格式化。请不要使用插件

example :

例子 :

// dd-mm-yy hh:mm:ss

// dd-mm-yy hh:mm:ss

function formatDate(date) {
    return ((date.getDate()<10?'0':'')+date.getDate()) + "-"+ 
        (((date.getMonth()+1)<10?'0':'') + (date.getMonth()+1)) + "-" + 
        date.getFullYear()  + " " +((date.getHours()<10?'0':'')+date.getHours()) + ":" + 
       (date.getMinutes()<10?'0':'') +  date.getMinutes() + ":" + 
       (date.getSeconds()<10?'0':'')  + date.getSeconds(); 
 }

*thank you @donot

*谢谢@donot

回答by Vaibs_Cool

Use jquery ui date parser.

使用 jquery ui 日期解析器。

http://docs.jquery.com/UI/Datepicker/parseDate

http://docs.jquery.com/UI/Datepicker/parseDate

This is the best function for parsing dates out of strings that I've had the pleasure to work with in js. And as you added the tag jquery it's probably the best solution for you.

这是从字符串中解析日期的最佳函数,我很高兴在 js 中使用它。当您添加标签 jquery 时,它可能是您的最佳解决方案。

回答by andi

.format() is not a valid Date method. JavaScript does not have an easy way to format dates and times with a user-specified format. The best you can do (without separate plugins) is to create your own string by getting each component of the date separately, and formatting/concatenating them.

.format() 不是有效的 Date 方法。JavaScript 没有一种简单的方法可以使用用户指定的格式来格式化日期和时间。您能做的最好的事情(没有单独的插件)是通过分别获取日期的每个组件并格式化/连接它们来创建自己的字符串。

回答by andi

I've used this before and it seems to work!

我以前用过这个,它似乎有效!

var dateString = endDate.toString("dd-m-yy hh:mm:ss");

var dateString = endDate.toString("dd-m-yy hh:mm:ss");