php Date转换为javaScript

时间:2017-07-21 12:40:19

标签: javascript php

需要帮助用JavaScript重写这个PHP代码

$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

我是JavaScript新手,这是我到目前为止所做的事情

var date='20170721';
varstamps = strtotime($date);
var newdate = date('d M Y',$stamps);
var data = explode(' ', $newdate);
$data[0].' '.strtoupper($data[1]).' '.$data[2];

4 个答案:

答案 0 :(得分:1)

为了获得更好的结果,您可以使用https://momentjs.com/ Moment js

包括使用时刻js <script type="text/javascript" src="bower_components/moment/moment.js"></script>

var date = '20170721'; moment(date).format('YYYY MMM DD');

答案 1 :(得分:0)

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();

参考:Javascript Date - set just the date, ignoring time?

答案 2 :(得分:0)

这是一个解决方案

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

答案 3 :(得分:0)

目前我不认为javascript支持日期转换,但这是一个解决方法

    
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>