I try to insert the date of today + 30 days. First of all I tried to display the current date with the following code:
<script>
var date = moment.unix(1414543560).locale('de').format("DD. MMMM YYYY");
document.write(date);
</script>
This displays the right day and Month, but unfortunately the Year is wrong (it's actually 2014)
How can I display the correct date of today + 30 days? Any ideas?
Try
var date = moment().add(30, 'days').locale('de').format("DD. MMMM YYYY");
document.write(date);
This takes the current date ( moment()
), adds 30 days ( add(30, 'days')
) and formats the date.
This should all be very obvious after you read the moment.js documentation.
function addDate(date,days){
var d=new Date(date);
d.setDate(d.getDate()+days);
var month=d.getMonth()+1;
var day = d.getDate();
if(month<10){
month = "0"+month;
}
if(day<10){
day = "0"+day;
}
var val = d.getFullYear()+"-"+month+"-"+day;
return val;
}
console.log(addDate("2014-10-10",30));
#output
2014-11-09
You can pass a UNIX timestamp to the Date
contructor in JavaScript set the date to 30 days in the future and pass that date to Moment.
// Construct date from UNIX timestamp
var date = new Date(1414543560 * 1000)
// Set date to 30 days in the future
date.setDate(date.getDate() + 30)
// Format date using Moment
var formatted = moment(date).locale('de').format('DD. MMMM YYYY')
Note that if your support target allows it you don't even need Moment anymore, you can use the built-in Internationalization API that comes with the browser.
// Construct date from UNIX timestamp var date = new Date(1414543560 * 1000) // Set date to 30 days in the future date.setDate(date.getDate() + 30) // Format date using Intl API var formatted = date.toLocaleDateString(['de-DE'], { day: '2-digit', month: 'long', year: 'numeric' }) document.write(formatted)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.