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

后端 未结 8 1727
余生分开走
余生分开走 2020-12-13 23:40

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 startDat         


        
相关标签:
8条回答
  • 2020-12-13 23:45

    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
    
    0 讨论(0)
  • 2020-12-13 23:52

    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)

    0 讨论(0)
  • 2020-12-13 23:58

    Try this:

    new Date().toLocaleFormat("%x");
    
    0 讨论(0)
  • 2020-12-14 00:01

    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',
    })
    
    0 讨论(0)
  • 2020-12-14 00:03

    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.

    0 讨论(0)
  • 2020-12-14 00:03

    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'
    
    0 讨论(0)
提交回复
热议问题