Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract one second from a given time

Tags:

php

datetime

time

I would like to add 1 day and then subtract ( minus ) 1 second from a given time.

I did:

$fromDate = date("Y-m-d", strtotime("2012-09-28")).' 00:00:00';
$date = strtotime(date("y-m-d H:m:s", strtotime($fromDate)) . " +1 day") - 1;
$toDate = date('Y-m-d H:m:s', $date);
echo $toDate;

but instead of 2012-09-28 23:59:59 it returns 2012-09-29 00:09:59

What am I doing wrong?

like image 899
glarkou Avatar asked Oct 14 '12 18:10

glarkou


People also ask

How do I subtract 1 second from a date in Excel?

Cell "A2" displays the current date and time. Custom format "dddd dd mmmm yyyy hh:mm:ss". Cell "A3" displays the current time minus 200 seconds. Cell "A4" displays the current time minus 200 seconds using the TIME function to return the correct decimal.


2 Answers

You're going round and round instead of getting to the point in your code. Here's my solution with DateTime objects:

$time = new DateTime("2012-09-28");
$time->modify("+1 day");
$time->modify("-1 second");

var_dump($time);

Or, if you just need the last second of the day, why not just:

$time = "2012-09-28";
$time .= " 23:59:59";

As it's unlikely that the number of seconds/minutes/hours a day to change.

like image 149
Madara's Ghost Avatar answered Oct 26 '22 00:10

Madara's Ghost


If I understand you right, you just want the last second in the given day, right?

If that's the case, then you could just have:

$theDate = "2012-09-28";
$fromDate = $theDate." 00:00:00";
$toDate = $theDate." 23:59:59";
like image 20
Niet the Dark Absol Avatar answered Oct 25 '22 22:10

Niet the Dark Absol