dtuy84033 2016-03-17 16:09
浏览 39
已采纳

来自自定义字符串php的Unix时间戳

I have a string of a letter and then a month followed by a year:

$followUpDate = 'M12-16'

I break up the month and the year:

$datestrip = explode("-", $followUpDate);
$part1     = substr($datestrip[0], 1); // Gives Month
$part2     = $datestrip[1]; // Gives Year

Now that I have broken up the month and year. I need to get the unix timestamp of said month and year.

So for this example the result of the unix timestamp should be 1480568400.

Thank you in advance!

  • 写回答

4条回答 默认 最新

  • doulidai6316 2016-03-18 11:00
    关注

    You can use DateTime::createFromFormat() (as other answers already mentioned). However, you have to pay attention to some minor details.

    Because you parse a string that contains a partial date (only the month and the year are specified), the rest of the fields (day of month, hour, minute, second) are set, by default, using the current time. Most probably, this is not what you want. I guess you want to get the start of the month (day 1, at midnight).

    You can get this by putting an exclamation mark (!) in front of the format string. It resets all the date components to the Unix epoch (1970-01-01 00:00:00 UTC).

    Also, the third parameter of DateTime::createFromFormat() is the timezone to use. If you don't pass it, PHP uses the default time zone set in php.ini or by the last call to date_default_timezone_set() (if there was any). This may or may not be what you need.

    $followUpDate = 'M12-16';
    
    // It seems like your timezone is US/Eastern (GMT+5 during the winter)
    $timezone = new DateTimeZone('US/Eastern');
    
    // Create a DateTime out of the provided string
    // The "!" character in front of the format resets all the fields
    // to the Unix epoch (1970-01-01 00:00:00 UTC) before parsing the string
    $date = DateTime::createFromFormat('!\Mm-y', $followUpdate, $timezone);
    
    // Display it; it displays 1480568400
    echo($date->format("U"));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常