Hello every i have date field of type string with iso format like this: const date = "2017-06-10T16:08:00: i want somehow to edit the string in the following format like this: 10-06-2017 but i'm struggling in achieving this. I cut the substring after the "T" character
-
use moment js for achieving thisViplock– Viplock2017-06-12 06:58:00 +00:00Commented Jun 12, 2017 at 6:58
-
why dont you check stackoverflow.com/a/25159403/4244010Srishin Kp– Srishin Kp2017-06-12 06:59:42 +00:00Commented Jun 12, 2017 at 6:59
-
... or stackoverflow.com/q/1056728/1169519Teemu– Teemu2017-06-12 07:00:07 +00:00Commented Jun 12, 2017 at 7:00
-
1Check this - momentjs.com/docs/#/displayingDASH– DASH2017-06-12 07:00:51 +00:00Commented Jun 12, 2017 at 7:00
Add a comment
|
7 Answers
It can be achieved without moment.js, but I suggest you use it
var date = new Date("2017-06-10T16:08:00");
var year = date.getFullYear();
var month = date.getMonth()+1;
var day = date.getDate();
if (day < 10) {
day = '0' + day;
}
if (month < 10) {
month = '0' + month;
}
var formattedDate = day + '-' + month + '-' + year
Comments
You can use the JavaScript date() built in function to get parts of the date/time you want. For example to display the time is 10:30:
<script>
var date = new Date();
var min = date.getMinutes();
var hour = date.getHour();
document.write(hour+":"+min);
</script>
To get the year, month, date, day of week use
getFullYear();
getMonth();
getDate();
getDay();
To get the date you posted:
1 Comment
lukas_o
var month = date.getMonth()+1; Month starts counting at 0, so January is 0, February is 1...
If you're looking to do this in vanilla javascript, @Ivan Mladenov's answer is great and can be consolidated slightly using padStart.
const date = new Date()
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
console.log(`${day}-${month}-${year}`)
Comments
I would like to suggest to use moment js find it - http://momentjs.com/docs/
and use it like
moment(date.toString()).format("MM/DD/YYYY")