如何在JavaScript中将完整日期转换为短日期? [英] How to convert a full date to a short date in javascript?

查看:199
本文介绍了如何在JavaScript中将完整日期转换为短日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的日期2010年1月9日,星期一我现在要将它转换为



我想要做到这一点

 $ / $> $ / $> $ / $>  var startDate =2010年1月9日星期一; 
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth()+ 1
var day = convertedStartDate.getDay();
var year = convertedStartDate.getFullYear();
var shortStartDate = month +/+ day +/+ year;

然而,它必须考虑日期格式不同,因为日期返回1而不是9。 / $>

解决方案

周(0 =太阳,1 =星期一,... 6 =星期六)。使用 getDate()返回月份当天的数字:

  var day = convertedStartDate.getDate(); 

如果您愿意,可以尝试将自定义格式函数添加到<$ c

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b return(this.getMonth()+ 1)+
/+ this.getDate()+
/+ this.getFullYear(); (b





完成后,可以调用 formatMMDDYYY() 放在 Date 对象的任何实例上。当然,这只是一个非常具体的例子,如果你真的需要它,你可以编写一个基于格式化字符串的通用格式化函数,类似于java的SimpleDateeFormat( http://java.sun.com/j2se/1.4.2/docs/api/java /text/SimpleDateFormat.html



(正切: Date 对象总是让我困惑。 getYear() vs getFullYear() getDate() vs getDay() getDate()取值范围为1..31,但 getMonth () from 0..11



这是一团糟,我总是需要窥视一下 http://www.w3schools.com/jsref/jsref_obj_date.asp

I have a date like this Monday, January 9, 2010

I now want to convert it to

1/9/2010 mm/dd/yyyy

I tried to do this

    var startDate = "Monday, January 9, 2010";
    var convertedStartDate = new Date(startDate);
    var month = convertedStartDate.getMonth() + 1
    var day = convertedStartDate.getDay();
    var year = convertedStartDate.getFullYear();
    var shortStartDate = month + "/" + day + "/" + year;

However it must be thinking the date is in a different format since day returns 1 instead of 9.

解决方案

The getDay() method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). Use getDate() to return a number for the day in month:

var day = convertedStartDate.getDate();

If you like, you can try to add a custom format function to the prototype of the Date object:

Date.prototype.formatMMDDYYYY = function(){
    return (this.getMonth() + 1) + 
    "/" +  this.getDate() +
    "/" +  this.getFullYear();
}

After doing this, you can call formatMMDDYYY() on any instance of the Date object. Of course, this is just a very specific example, and if you really need it, you can write a generic formatting function that would do this based on a formatting string, kinda like java's SimpleDateeFormat (http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html)

(tangent: the Date object always confuses me... getYear() vs getFullYear(), getDate() vs getDay(), getDate() ranges from 1..31, but getMonth() from 0..11

It's a mess, and I always need to take a peek. http://www.w3schools.com/jsref/jsref_obj_date.asp)

这篇关于如何在JavaScript中将完整日期转换为短日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆