Reputation: 48
Needs help in rewriting this php code in JavaScript
$date='20170721';
$stamps = strtotime($date);
$newdate = date('d M Y',$stamps);
$data = explode(' ', $newdate);
echo $data[0].' '.strtoupper($data[1]).' '.$data[2];
//output 2017 JUL 21
I am new in JavaScript this is what i have done so far
var date='20170721';
varstamps = strtotime($date);
var newdate = date('d M Y',$stamps);
var data = explode(' ', $newdate);
$data[0].' '.strtoupper($data[1]).' '.$data[2];
Upvotes: 0
Views: 79
Reputation: 43
Currently i dont think javascript supports date conversions as this, but heres a work around
var str='20170721';
var datee=str.slice(0,4)+'-'+str.slice(4,6)+'-'+str.slice(6,8);
var date = new Date(datee);
var newDate = date.toString('yyyy MMMM dd');
console.log(newDate);
// Or you can decide to do this without any external library
var num =parseInt(str.slice(4,6));
var month='';
switch(num)
{
case 0:
month="January";
break;
case 1:
month="February";
break;
case 2:
month="March";
break;
case 3:
month="April";
break;
case 4:
month="May";
break;
case 5:
month="June";
break;
case 6:
month="July";
break;
case 7:
month="August";
break;
case 8:
month="September";
break;
case 9:
month="October";
break;
case 10:
month="November";
break;
case 11:
month="December";
break;
default:
month="Invalid month";
}
console.log(str.slice(0,4)+' '+month+' '+str.slice(4,6));
<script src="http://cdnjs.cloudflare.com/ajax/libs/datejs/1.0/date.min.js"></script>
Upvotes: 0
Reputation: 29307
Here's a solution
var date = '20170721';
var year = date.slice(0,4),
month = date.slice(4,6),
day = date.slice(-2);
// create new Date obj
date = new Date(year, month, day);
// format using toLocaleDateString
console.log(new Date(year, month, day).toLocaleDateString('en-GB'));
// custom format
console.log(date.getFullYear() + ' ' + (date.getMonth()) + ' ' + date.getDate())
//output 2017 JUL 21
Upvotes: 0
Reputation: 882
Php :
$date='20170721';
$stamps = strtotime($date);
Javascript :
var idate = 1500588000; // unix timestamp returned from php ($stamps variable)
var jdate = new Date(idate * 1000);
var day = jdate.getDate();
var month = jdate.getMonth();
var year = jdate.getYear();
var fulldate = jdate.toDateString();
Reference : Javascript Date - set just the date, ignoring time?
Upvotes: 0
Reputation: 265
For better Result you can user https://momentjs.com/
Moment js
include moment js using
<script type="text/javascript" src="bower_components/moment/moment.js"></script>
var date = '20170721';
moment(date).format('YYYY MMM DD');
Upvotes: 1