javascript 在Javascript中以DD/MM/YYYY格式获取昨天日期的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16686640/
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
Function to get yesterday's date in Javascript in format DD/MM/YYYY
提问by Joe
I've been looking for a while to get yesterday's date in format DD/MM/YYYY. Here's my current code:
我一直在寻找以 DD/MM/YYYY 格式获取昨天的日期。这是我当前的代码:
var $today = new Date();
var $dd = $today.getDate();
var $mm = $today.getMonth()+1; //January is 0!
var $yyyy = $today.getFullYear();
if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;
With this, I get today's date in format DD/MM/YYYY (thanks SO). But when I try this:
有了这个,我以 DD/MM/YYYY 格式获得今天的日期(感谢 SO)。但是当我尝试这个时:
var $yesterday = $today.getDate()-1;
as recommended on this site somewhere else (lost the link), I get an error saying that getDate() was not found for this object.
按照本网站其他地方的建议(丢失链接),我收到一条错误消息,指出找不到此对象的 getDate()。
I'm using my script with Sahi, but I don't think it's linked, as Sahi has no trouble with Javascript.
我正在将我的脚本与 Sahi 一起使用,但我认为它没有关联,因为 Sahi 对 Javascript 没有任何问题。
Thank you in advance.
先感谢您。
回答by Sam
The problem here seems to be that you're reassigning $today
by assigning a string to it:
这里的问题似乎是您$today
通过为其分配一个字符串来重新分配:
$today = $dd+'/'+$mm+'/'+$yyyy;
Strings don't have getDate
.
字符串没有getDate
。
Also, $today.getDate()-1
just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:
另外,$today.getDate()-1
只给你一个月中的第几天减一;它没有给你“昨天”的完整日期。试试这个:
$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.
Then just apply the formatting code you wrote:
然后只需应用您编写的格式代码:
var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!
var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;
Because of the last statement, $yesterday
is now a String
(nota Date
) containing the formatted date.
由于最后一条语句,$yesterday
现在是一个String
(不是a Date
)包含格式化的日期。
回答by katranci
Try this:
试试这个:
function getYesterdaysDate() {
var date = new Date();
date.setDate(date.getDate()-1);
return date.getDate() + '/' + (date.getMonth()+1) + '/' + date.getFullYear();
}
回答by madflow
You override $today
in the if statement.
您$today
在 if 语句中覆盖。
if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $today = $dd+'/'+$mm+'/'+$yyyy;
It is then not a Date() object anymore - hence the error.
然后它不再是 Date() 对象 - 因此出现错误。