I've been working on a blog commenting system and have been inserting the datetime with NOW(), and I can't quite manage to pull it back into manageable variables,
I've tried using strtotime like following
$date_time1 = strtotime( $row['chron']);
echo $date_time1;
also with mktime
$timeywimey = mktime ( $row['chron'] );
both of these are turning 2011-03-24 12:01:59 into 1300964519
Iif possible I would be looking to split these down into yy,mm,dd hh,mm
Although it's just basic string manipulations should be known to every PHP user, you shouldn't split this value but rather format it in desired format, by using either SQL date_format() function or PHP date() one. For the latter it would be
$date = date("format",strtotime($row['chron']));
for sake of splitting practice, you have either to use some regular expression(harder) or couple calls of explode(), to split value into date ant time parts and then consequently split these into smaller parts.
Related
There is a requirement to send a date inside a JSON post using PHP in this following format
\/Date(410256000000-0800)\/
How do I convert a standard dd-mm-yyyy h:i:s datetime like 01-01-2013 12:00:00 to that format in PHP? Just need to know what values correspond to what in that format, not really look for a stringify things answer.
This should do it:
$dateTime = DateTime::createFromFormat('d-m-Y H:i:s', '01-01-2013 12:00:00');
$requiredJsonFormat = sprintf(
'\/Date(%s%s)\/',
$dateTime->format('U') * 1000,
$dateTime->format('O')
);
echo $requiredJsonFormat; // prints '\/Date(1357038000000+0100)\/'
I leave it up to you to find what the formats U and O do from http://php.net/date.
An alternative would be to use PHP's DOTNET API and use the DataContractJsonSerializer class directly from PHP. However, you'd need .NET installed on the server and using PHP's DOTNET API is rather arcane.
The more interesting part is why you need this format at all. This is explained in a blogpost at http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx
But because of a strange oversight in the EcmaScript specs, there is no standard way of describing dates in JSON. […] Our current approach is using a small loophole in the JSON specs. In a JSON string literal, you may (or may not) escape some characters. Among those characters, weirdly enough, there is the slash character ('/'). […] The new format is "/Date(1198908717056)/" where the number is again the number of milliseconds since January 1st 1970 UTC […] The point is that this disambiguates a date literal from a string that looks like the same date literal, while remaining pure JSON that will be parsed by any standard JSON parser. Of course, a parser that doesn't know about this convention will just see a string, but parsers that do will be able to parse those as dates without a risk for false positives
We created a package for this: https://github.com/webapix/dot-net-json-date-formatter
It uses a similar approach than the previous answer, tested on PHP versions >= 5.6.
use DateTime;
use DateTimeZone;
use Webapix\DotNetJsonDate\Date;
$date = DateTime::createFromFormat(
'd-m-Y H:i:s',
'01-01-2013 12:00:00',
new DateTimeZone('+0000')
);
Date::toJsonDate($date); // returns '/Date(1357041600000+0000)/'
I am rebuilding a web application from an old one with many inconsistencies. I have to migrate all the data over from the old database to our new structure.
In the old database, dates were stored in the MySQL DB as VARCHAR. We are based in the UK, so dates were written in the format DD/MM/YYYY. I need to convert these dates to MySQL's native DATE() format.
Problem is this - PHP defaults to assuming the dates are in 'American' format (MM/DD/YYYY) because they were originally split with / rather than - - and - forces PHP to assume they are 'European' format.
I am doing this so far to convert them:
$start_date = date('Y-m-d', strtotime($query->row('startdate')));
Where $query->row('startdate') is the column in the old database which was storing the dates. Problem is, I need to first switch all the 21/03/1994s to 21-03-1994.
How can I do this?
$start_date = date('Y-m-d', strtotime(str_replace('/', '-', $query->row('startdate'))));
Or better yet - just change the data in the database:
UPDATE `table` SET `startdate` = REPLACE(`startdate`, '/', '-');
... and then convert the field to type DATE.
---- EDIT ----
Actually, Col. Shrapnel has a point ... I'd overlooked the fact that the date needs reversing as well so it's YYYY-MM-DD; assuming the original date is in the format DD/MM/YYYY a better query might be something like:
UPDATE `table` SET `date` = CONCAT(SUBSTRING(`date`, 7), '-', SUBSTRING(`date`, 4, 2), '-', SUBSTRING(`date`, 1, 2))
Which will reverse the component parts into a string that can be converted to a DATE ... it won't quite work if the original date string doesn't use leading zeroes 1/6/2011 for instance... would need to do something a little cleverer in that case.
WHY bother with all this date time stuff when you need mere a simplest string manipulation of 2 moves long?
$tmp = explode("/",$query->row('startdate'));
$date = "$tmp[2]-$tmp[1]-$tmp[0]";
but, as chris said, you dno't have to involve PHP in this operation as you can convert it using single SQL query using similar string manipulations in the query.
MySQL has a Replace() function that may be the easiest way to do this.
This is the 5.0 API reference:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
Use str_replace like this:
$start_date = date('Y-m-d', strtotime(str_replace('-','/',$query->row('startdate'))));
That is of course ugly and quick solution - YMMV.
If you're bound to PHP, why not parse the data, normalize it and then continue? E.g. with sscanf:
$r = sscanf($varcharDate, '%d/%d/%d', $day, $month, $year);
if ($r !== 3)
{
throw new Exception(sprintf('Invalid date format given: %s', $varcharDate));
}
I'm currently scraping content from a website using PHP and YQL. I need to convert an awkward date format into a UNIX timestamp so it can be formatted into a MySQL compatible date. I have tried using strtotime() but to no avail. Maybe a regular expression is the answer?
Examples of dates
08Dec10
06Aug10
29Jul10
07Jun10
04May10
Dan
If you are using PHP 5.3+
Then then DateTime::createFromFormat function is perfect for your needs..
$date = DateTime::createFromFormat('dMy', '08Dec10');
Then you can do whatever you want with the date, if you need it in a different format:
echo $date->format('Y-m-d');
If you are ever able to use the DateTime functions, several available from 5.2+ and more added in 5.3 then you should. Compared to the other functional solutions, the DateTime approaches are much more readable.
Also in all solutions, whether functional or using the DateTime object, check the return values. Both createFromFormat and strptime return false on error. So you can log the error and determine what the issue was.
Note: strptime is not available on Windows.
One solution is to use strptime:
$parts = strptime($str, '%d%b%y');
and then you can pass the values to mktime:
$timestamp = mktime(0,0,0,$parts['tm_mon']+1, $parts['tm_mday'], $parts['tm_year']+1900);
Break up the date components using substr and use strtotime to put it all together again.
<?php
strtotime('20'. substr($time, 5, 2). '-'. substr($time, 2, 3). '-'. substr($time, 0, 2));
?>
well, I"ve got a time format of the type: 2011-02-16T01:25:50+04:00
I want to strip the +04:00 from the end of the string. How to do it?
I am converting a timestamp from mysql to ISO 8601 format using this function:
$timeagotime = date('c',strtotime($row['created_at']));
where $timeagotime contains the value: 2011-02-16T01:25:50+04:00
Refer to the documentation for php's date function: http://php.net/manual/en/function.date.php
You need to use a different format string. For instance,
date('Y-m-d',strtotime($row['created_at']));
Givens you "2011-02-16". There are a number of format strings... check out the doc.
You could use substr() to remove it, or just generate a date without it in the first place, though you couldn't use the 'c' formatting option, since that'd just add the timezone on again.
$timeagotime = substr($timeagotime, 0, 19)
$timeagotime = date('Y-m-dTG:i:s', strtotime(...));
If you absolutely don't need the end then you can use the following. Otherwise I'd suggest using a different way to generate your date from the table. PHP Date
$timeagotime = substr(date('c',strtotime($row['created_at'])), 0, 19);
What is the best way in php to take the following string mm[some char]dd[some char]yyyy and translate it to yyyymmdd?
I will probably want in the future, according to local do the same with dd[some char]mm[some char]yyyy.
If there is a way that already uses the Zend Framework API, the better
<?php
$str = '08-24-1989'; // can be in any recognizable date format.
$new_str = date('Ymd', strtotime($str)); // produces "20090824".
?>
You can replace Ymd in the second statement above with any date format characters found here.
If you're looking to use Zend's Zend_Date framework, check out some examples and documentation here. Quite frankly though, the PHP functions are a lot simpler and easier to use in your case.
date('Ymd', strtotime($time));
Strtotime is absolutely the best tool to translate almost any time format into a standard one that you can then use Date to put into the format you want.
Because you question title says MySQL Dates, this is the string format that mysql uses.
date('Y-m-d h:i:s', strtotime($time));
Unless [some char] varies , use the mysql str_to_date function, e.g. STR_TO_DATE('12|23|2009','%m|%d|%Y');
I would absolutely use TIMESTAMP for any date storage. It's incredibly easy to handle time differences (like SELECT ... WHERE date BETWEEN 2138728753 AND 376251237) and can be translated to any locale pretty easily :)