Remove time part of a timestamp - php

How can I remove time part of a timestamp?
So for example turn 1310571061 to 1310565600 which is the plain date timestamp.

strtotime(date("Y-m-d", 1310571061));
That should do it for you.

In case you wanted a mathematical solution:
$time=1310571061;
echo floor($time/86400)*86400;
There are 86,400 seconds in 24 hours (which is the length of a typical day, but not all... see DST). Since our timestamps are in UTC, this shouldn't be a problem. You can divide that by the number of seconds in a day, drop the remainder, and multiply back out.

Using a DateTime object can be helpful, and also can make the code more readable...
$dt = new DateTime();
$dt->setTimestamp(1310571061);
echo $dt->format('Y-m-d, H:i:s') . "\r\n";
$dt->setTime(0, 0, 0);
echo $dt->format('Y-m-d, H:i:s');
Result...
2011-07-14, 03:31:01
2011-07-14, 00:00:00
The choice of whether to use raw timestamps or DateTime objects will depend a lot on the implementation needs, but generally speaking DateTime objects will go a long way towards reducing confusion and errors that can crop up especially around Timezone issues and Daylight Saving Time issues.

Try:
<?php
$ts = '1310571061';
echo strtotime(date('Y-m-d 00:00:00', $ts));
?>

$pubdate='2003-02-19T00:00:00.000-05:00';
$da = strtotime($pubdate);
echo $dat = date('Y-m-d', $da);
The answer is like :"2003-02-19"
Thank You

You could do:
$date = strotime(date("y/m/d", $timestamp));

This is what I usually do:
your_timestamp = pd.to_datetime(your_timestamp.strftime(format="%x"))
The function strftime will convert your_timestamp to a string without the time component. Then the function pd.to_datetime will convert it back to a Timestamp without the time component.

Related

Best way of converting date string to timestamp?

It's been a long long day and it's getting close to 2am here.
I was wondering if someone could give me some guidance towards the best solution of converting this string to timestamp and then converting it date time so it can be inserted into a database.
I know there is ways like this:
$d = new DateTime('26-10-2018');
$timestamp = $d->getTimestamp(); // Unix timestamp
$formatted_date = $d->format('Y-m-d'); // 2018-26-10
But is there anything which accepts the hours and minutes aswell?
$datestring = "26-10-2018 09:30";
How about this date('Y-m-d H:i:s', strtotime('26-10-2018 09:30'));

How to get any datetime in microseconds from any date in php

i'm wondering if there's a way to get any datetime in microseconds.
I was looking forward microtime(), but it just returns the date in the moment.
Anyone knows if is this possible?
I have my date given like: Y-m-d H:i:s.u.
I was thinking about something like (Y-1970)*31556926 + m*151200+d*86400+h*3600+m*60+s.u
but I don't know if that's why i'm a beginner on programming, but i can't think in a way to separate each: Y,m... to do the math.
Would appreciate any help/suggestions.
You can do this with DateTime:
$date = DateTime::createFromFormat('Y-m-d H:i:s.u', '2000-01-01 13:12:12.129817');
echo $date->format('U.u');
//prints: 946728732.129817
What I would do is simply split apart your input format like this:
Y-m-d H:i:s and u
You should be able to do this by exploding on . in your input formatted date string. Then just calculate the UNIX timestamp on the whole second portion. Finally just add your fraction second portion back to the timestamp (via either string concatenation of arithmetic depending on whether you want string or float as result).
No it's not possible. Timestamps are integers internally, describing the seconds from 01.01.1970 GMT. Regardless if you are using a 32 or 64 bit system, the microseconds from 1970 would lead to an overflow as there has much too many of them gone.
You updated the question.. Yes, it is possible to display the current time in microsends using microtime():
$microtime = microtime();
// will return something like:
// 0.40823900 1381181037
// where the first are the micros and the last a regular time stamp
list($micros, $timestamp) = explode(' ', $microtime);
echo date('Y-m-d H:i:s', intval($timestamp)) . '+'
. (floatval($micros) * 1000000) . 'msec';

Format Unix Timestamp with Timezone?

Lets say I've got my Unix Timestamp of 1373623247. Now I understand that the timestamps are just seconds since X. The issue I have is the formatting of it.
The server I use is hosted in Germany, however I am in the UK so the output is 12-07-13 12:01:01, when actually its only 11:01:01 here.
The code I am using is as below:
$date = 1373623247;
echo date("j-m-y h:i:s",$date);
What I did was use date_create and timezone as follows:
$date1 = date("j-m-y h:i:s",$date);
$dateobj = date_create("$date1", timezone_open('Europe/London'));
echo date_format($dateobj,"j-m-y h:i:s") . "\n";
The issue I now have is that it's actually adjusted the date to tomorrow, and hasn't altered the time!
You do not need to involve date at all:
$date = 1373623247;
$dateobj = date_create_from_format("U", $date);
date_timezone_set($dateobj, timezone_open('Europe/London'));
echo date_format($dateobj,"j-m-y h:i:s") . "\n";
This code converts the timestamp directly to a DateTime instance using the U format specifier. It's both shorter and cleaner to not work with date, as you don't need to worry about the server's default timezone at all.
Pro tip: date and strtotime get much coverage, and in certain cases are very convenient, but DateTime can do everything on its own and IMHO results in code that is much more maintainable.

strtotime / 86400 not returning even number of days

I am having a strange result with PHP Version 5.3.1, can anyone explain the below result?
$secondsDiff = strtotime(date("2011-11-10")) - strtotime('2011-07-15');
return ($secondsDiff/86400);
it returns 117.958333333??
When I use dates closer together it generally works.
I had a look through the docs, but couldnt find any reference to this. Is this a known php bug that I just need to learn to live with or am I missing something very obvious?
This is probably due to a DST switch, which will increase or decrease the length of the period by an hour.
This could be fixed by rounding, or - more elegantly - by PHP 5.3's fancy new DateInterval class which can format periods as days and more.
Stolen from the manual:
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
?>
Don't convert seconds into days by dividing them by 86400. It will work most of the time, sure, but in some circumstances it will return an ugly number. That is what is happening here. The usual culprit is a switch into or out of daylight savings time.
The slow way to do it is to use a loop and calls to mktime(); the modern way is to use the DateInterval class.
The strtotime() function uses the TZ environment variable. This means that when you convert that date, you end up with a timestamp that isn't exactly at midnight, unless you happen to have your timezone set up for GMT.
So, if you are in an area with daylight savings time, then a date in November will be an hour off than one in July. You can easily test this using the two dates you provided. On my server, one appears at 4:00AM, and the other at 5:00AM on their respective dates.
Another solution: Add UTC to the string as in
$datetime1 = new DateTime('2009-10-11 UTC');
$datetime2 = new DateTime('2009-10-13 UTC');

Displaying timezones without using UTC

I've been reading up on how to do this all morning, and the general consensus is this: store your timestamps in UTC and calculate the offset from there.
However, like most people, I am maintaining an existing codebase and I can't change the way we store our dates. At least, not in the allotted time frame.
So my question is, can I safely do something like this?
// this is my time zone
$timestamp = strtotime($timestampFromDatabase);
date_default_timezone_set('America/New York');
$tz = date_default_timezone_get();
// this is theoretically their timezone, which will eventually
// be taken from a session variable
date_default_timezone_set('Europe/Paris');
$offset = time() - $timestamp;
$timestamp -= $offset;
// now that I have the offset, display dates like this
date('r', $timestamp);
Some people have advised against doing date arithmetic, but is what I'm doing here wrong? Is there a better way? Are there pitfalls I need to watch out for? I'm particularly interested in what kind of bugs this method could produce, and if any, who will they affect?
My boss is the kind of guy that doesn't care if the bug only affects 1% of the user base.
Edit: Can I make this any clearer? I don't seem to have too many takers on this. Anyone? Even a vague suggestion or a link would be immensely helpful.
The short answer is that timezones are tricky to work with and no-one wants to tackle the difficult questions!
The longer, answer is this:
Firstly, you need to create a representation of your date, in their current timezones. The following are equivalent:
date_default_timezone_set('America/New York');
$date = new DateTime(null);
OR
$date = new DateTime(null, new DateTimeZone('America/New York'));
This gives you a date with zone set to America/New York. We can easily convert it to the user timezone, in this case Europe/Paris with the next line:
$date->setTimezone(new DateTimeZone('Europe/London'));
You can use the following line to get the date/time represented at any point.
echo $date->format('d/m/Y H:i:s');
I strongly recommend this over arithmetic, as the built in PHP functions have knowledge of daylight saving times and lots of complicated things that you won't get right.
My test script in full:
date_default_timezone_set('America/Belize');
$date = new DateTime(null);
echo $date->format('d/m/Y H:i:s') . '<br>';
$date->setTimezone(new DateTimeZone('Europe/London'));
echo $date->format('d/m/Y H:i:s') . '<br>';

Categories