简体   繁体   English

如何在 javascript 中将完整日期转换为短日期?

[英]How to convert a full date to a short date in javascript?

I have a date like this Monday, January 9, 2010我有一个像这样的日期 2010 年 1 月 9 日星期一

I now want to convert it to我现在想将其转换为

1/9/2010 mm/dd/yyyy 2010 年 1 月 9 日 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.但是它必须认为日期的格式不同,因为 day 返回 1 而不是 9。

The getDay() method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). getDay()方法返回一个数字来指示星期几(0=Sun,1=Mon,... 6=Sat)。 Use getDate() to return a number for the day in month:使用getDate()返回一个月中的某一天的数字:

var day = convertedStartDate.getDate();

If you like, you can try to add a custom format function to the prototype of the Date object:如果你愿意,你可以尝试在Date对象的原型中添加自定义格式函数:

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.执行此操作后,您可以对Date对象的任何实例调用formatMMDDYYY() 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 )当然,这只是一个非常具体的例子,如果你真的需要它,你可以编写一个通用的格式化函数,它会根据格式化字符串来做这件事,有点像 java 的 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 (切线: Date对象总是让我感到困惑...... getYear() vs getFullYear()getDate() vs getDay()getDate()范围从 1..31,但getMonth()从 0..11

It's a mess, and I always need to take a peek.一团糟,我总是需要偷看一眼。 http://www.w3schools.com/jsref/jsref_obj_date.asp ) http://www.w3schools.com/jsref/jsref_obj_date.asp )

Here you go:给你:

(new Date()).toLocaleDateString('en-US');

That's it !!就是这样!!

you can use it on any date object您可以在任何日期对象上使用它

let's say.. you have an object called "currentDate"比方说..你有一个名为“currentDate”的对象

var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy

(or) (或)

If you want it in local format then如果你想要本地格式,那么

currentDate.toLocaleDateString(); // gives date in local Format

Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion.内置的toLocaleDateString()完成这项工作,但它会删除日期和月份的前导 0,所以我们会得到类似“1/9/1970”的东西,在我看来这并不完美。 To get a proper format MM/DD/YYYY we can use something like:要获得正确的MM/DD/YYYY格式,我们可以使用以下内容:

new Date(dateString).toLocaleDateString('en-US', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
})
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)"); 
document.getElementById("demo").innerHTML = d.toLocaleDateString();

date.toLocaleDateString('en-US') works great. date.toLocaleDateString('en-US')效果很好。 Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString这里有一些关于它的更多信息: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

This is a great place to use Moment.js 这是一个使用Moment.js的好地方

JavaScript is notorious for handling dates poorly. JavaScript因处理日期而臭名昭着。 There are a few gotchas that you'll be susceptible to if you simply append a date together like 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;
  • JavaScript implicitly adds a DateTime offset that could push the date into the next day if your user is on the opposite side of the International Date line. 如果您的用户位于国际日期行的另一侧,则JavaScript会隐式添加DateTime偏移量,该偏移量可能会将日期推送到第二天。
    • ie the client is +/- 12 hours or more 即客户是+/- 12小时或更长时间
  • JavaScript will not give you a full 10 characters for the appended case given. JavaScript不会为给出的附加案例提供完整的10个字符。
    • ie Your service may be expecting "Short Date '01/01/2015'" but if you simply append as in the above case you will end up with '1/1/2015' 即您的服务可能会期待“短期'01 / 01/2015'”,但如果您只是按照上述情况附加,您将最终得到'1/1/2015'

You should use Moment.js to handle this case. 您应该使用Moment.js来处理这种情况。 There are tons of built in formats for dates and you can manually specify them without the risk of the date time offset being added or the format coming out different than what you expect. 日期有大量内置格式,您可以手动指定它们,而不会有添加日期时间偏移或格式与预期不同的风险。

For example: moment('01/01/2001').format('L'); 例如: moment('01/01/2001').format('L'); Will result in '01/01/2001' 将导致'01 / 01/2001'

Take a look at this moment.js sandbox on jsfiddle 看看这个时刻.js沙盒上的jsfiddle

I wanted the date to be shown in the type='time' field.我希望日期显示在 type='time' 字段中。

The normal conversion skips the zeros and the form field does not show the value and puts forth an error in the console saying the format needs to be yyyy-mm-dd.正常转换会跳过零,表单字段不显示值,并在控制台中显示错误,指出格式需要为 yyyy-mm-dd。

Hence I added a small statement (check)?(true):(false) as follows:因此,我添加了一个小语句 (check)?(true):(false) 如下:

makeShortDate=(date)=>{
yy=date.getFullYear()
mm=date.getMonth()
dd=date.getDate()
shortDate=`${yy}-${(mm<10)?0:''}${mm+1}-${(dd<10)?0:''}${dd}`;
return shortDate;
}

Although this question posted long long time ago, the proper way to do this is:虽然这个问题很久以前就发布了,但正确的方法是:

Intl.DateTimeFormat("en").format(new Date())

Any way, the Intl (international) object has many options you can pass to like to enforce tow digits etc. You all can look at it here无论如何,国际(国际)object 有许多选项可以传递给喜欢强制执行两位数等。你们都可以在这里查看

I was able to do that with :我能够做到这一点:

var dateTest = new Date("04/04/2013");
dateTest.toLocaleString().substring(0,dateTest.toLocaleString().indexOf(' '))

the 04/04/2013 is just for testing, replace with your Date Object. 04/04/2013 仅用于测试,请替换为您的日期对象。

You could do this pretty easily with my date-shortcode package:你可以用我的date-shortcode包很容易地做到这一点:

const dateShortcode = require('date-shortcode')

var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'

试试这个:

new Date().toLocaleFormat("%x");

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

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