开发者

How to convert a full date to a short date in javascript?

开发者 https://www.devze.com 2022-12-15 19:08 出处:网络
I have a date like this Monday, January 9, 2010 I now want to convert it to 1/9/2010mm/dd/yyyy开发者_开发知识库

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.


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"

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


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)


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. To get a proper format MM/DD/YYYY we can use something like:

new Date(dateString).toLocaleDateString('en-US', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
})

Alternative: We can get similar behavior using Intl.DateTimeFormat which has decent browser support. Similar to toLocaleDateString(), we can pass an object with options:

const date = new Date('Dec 2, 2021') // Thu Dec 16 2021 15:49:39 GMT-0600
const options = {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
}
new Intl.DateTimeFormat('en-US', options).format(date) // '12/02/2021'


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. Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString


I wanted the date to be shown in the type='time' field.

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.

Hence I added a small statement (check)?(true):(false) as follows:

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


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.


You could do this pretty easily with my date-shortcode package:

const dateShortcode = require('date-shortcode')

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


Try this:

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

精彩评论

暂无评论...
验证码 换一张
取 消