问题
I have date yyyy/mm/dd format in JavaScript and I want to display it in textbox by this format example: January 1 2014.
function displayinTextbox(){
var datetodisplay = new Date('2014/01/01'); //i want to convert it first in this format (January 1 2014)
var convertedDate = ///how??????
document.getElementById('date').value = convertedDate ;
}
回答1:
The Date
object provides various methods to access the different parts that make the date/time data.
In your case displaying the month as a name instead of a number will require mapping the month values (from 0 to 11) to the month name (from "January" to "December").
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var convertedDate = monthNames[dateToDisplay.getMonth()] + " " + dateToDisplay.getDate() + " " + "dateToDisplay.getFullYear();
If you have to deal with multiple languages and "pretty" formats, you may want to have a look at a formatting library such as Moment.js.
回答2:
function displayinTextbox(){
var datetodisplay = new Date('2014/01/01');
var months = ["January", "February", "March", "April", "May", "June", "July", August", "September", "October", "November", "December"];
var convertedDate = months[datetodisplay.getMonth()] + " " + datetodisplay.getDate() + " "+datetodisplay.getUTCFullYear();
document.getElementById('date').value = convertedDate ;
}
回答3:
Try this:
function displayinTextbox(){
var datetodisplay = new Date('2014/01/01');
var convertedDate = datetodisplay.toDateString();
document.getElementById('date').value = convertedDate ;
}
回答4:
getDate(): Returns the day of the month.
getDay(): Returns the day of the week. The week begins with Sunday (0 - 6).
getFullYear(): Returns the four-digit year.
getMonth(): Returns the month.
getYear(): Returns the two-digit year.
getUTCDate(): Returns the day of the month according to the Coordinated Universal Time (UTC).
getUTCMonth(): Returns the month according to the UTC (0 - 11).
getUTCFullYear(): Returns the four-digit year according to the UTC.
Read this article
回答5:
I recommend you to use Moment.js library.
What you need can be simply done with Moment.js.
var str = '2014/01/01';
var formatted = moment(str, 'YYYY/MM/DD').format('MMMM D YYYY');
console.log(formatted);
http://jsfiddle.net/949vkvjk/2/
来源:https://stackoverflow.com/questions/25551322/convert-date-yyyy-mm-dd-to-mm-dd-yyyy