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条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图