PHP date format converting - php

Here is what I have:
$dateFormat = 'M d, Y';
$dateString = 'January 23, 2010';
What I need is a timestamp of $dateString so I can do this:
$newFormattedDate = date('Y-m-d', $timestamp);
I tried to use strtotime function but it tries to find out the format itself and doesn't work always. In my situation I know both the date string and date format.
How can I set $timestamp to an appropriate value for use with the date function?
EDIT: I need this to work in both Linux and Windows environments.
EDIT: The solution must support PHP version 4 or higher
EDIT: MySQL has a function called STR_TO_DATE which takes a date string and a date format and returns Y-m-d formatted date string. Any equivalent function for php works for me also.

As of PHP5.3 you can use the DateTime API
$dt = date_create_from_format('M d, Y', 'January 23, 2010');
echo date_timestamp_get($dt);
or with OOP notation
$dt = DateTime::createFromFormat('M d, Y', 'January 23, 2010');
echo $dt->getTimestamp();
Note that while DateTime is available in PHP < 5.3, the methods used above are not and while you could simulate ->getTimestamp() with ->format('U'), there is no easy workaround for createFromFormat()
An alternative would be to use Zend_Date from Zend Framework:
$date = new Zend_Date('Feb 31, 2007', 'MM.dd.yyyy');
echo $date->get(Zend_Date::TIMESTAMP);

Use strptime, mktime and strftime:
$ftime = strptime($dateString, $dateFormat);
$timestamp = mktime($ftime['tm_hour'], $ftime['tm_min'], $ftime['tm_sec'], 1,
$ftime['tm_yday'] + 1, $ftime['tm_year'] + 1900);
echo strftime('Y-m-d', $timestamp);
Please note that strptime is not implemented on Windows platforms.
Note that the arguments to mktime are somewhat unusual - strptime returns a day of the year (between 0-365, inclusive) rather than a day of the month and a month, so we set the month parameter to mktime to 1, and add 1 to the day of the year. Also, strptime returns years since 1900 for the year value it returns, so we need to add 1900 to the year before passing it through to mktime.
Also, you might want to check whether $ftime is FALSE before passing it into mktime. strptime returning FALSE denotes that the inputs $dateString is not a valid date format according to $dateFormat.

Given my understanding of the question and what is available in PHP, you need to relax your expectations somewhere or other.
A 'simple' solution (which has already been discounted) would be to force using PHP 5.3 and the tools available in it.
A less simple solution would be to take those additions and port them over to PHP-land (with PHP 4 compatibility, good luck).
Another route of exploration would be to consider the occasions where strtotime does not work for you and working around those limitations.
How widely variant are your format strings? It may be possible to come up with a solution mapping format strings to functions/methods (to do that date parsing) providing they're pretty restricted.

$dateFormat = 'M d, Y'
$timestamp = strtotime($dateString);
echo date($dateFormat, $timestamp);
if i haven't misunderstand your question you can try the code above..

Related

PHP 6 digit date code display in human readable format

I have a set of dates that are formatted like this...
197402
192201
184707
The first four digits represents the year and the remaining two the month. I am trying to output these in this format
February 1974
January 1922
July 1847
I have tried passing it to the date function like this...
echo date ('F Y', 197402)
But this is giving me January 1970 everytime so I assume I have misunderstood how the date function works, can anyone help?
You're getting "January 1970" as an output, because you tried to create a date from the timestamp 197402, which is seconds from January 1st, 1970. If you output the full string from that (with seconds and whatnot), you'll see it's a valid timestamp, producing an actual date, but they all end up in the start of January 1970, see this online demo.
That format, YYYYMM, isn't a recognizable format for most functions. You need to split it up, if you know the format will be in that way - and use that data instead. You can use substr() to split the string, and then convert the numerical month to the string associated with that month, with the help of date() and mktime() (since you just specify the year and month).
The following snippet
$arr = [197402, 192201, 184707];
foreach ($arr as $v) {
$year = substr($v, 0, 4);
$month = substr($v, 4, 2);
echo date("F Y", mktime(0, 0, 0, $month, 0, $year))."<br />"; // mktime() produces a valid timestamp based on just month and year
// Alternatively, drop mktime() and use strtotime() and create from a standard format,
// while specifying a date in the month (which won't matter to the output)
// echo date("F Y", strtotime("$month/01/$year"))."<br />";
}
will output
February 1974
January 1922
July 1847
Alternatively, you can use the DateTime class (which is a lot simpler to work with), and create from a given format with date_create_from_format()
foreach ($arr as $v) {
echo date_create_from_format('Yh', $v)->format('F Y')."<br />";
}
This will generate the same output as above.
References
http://php.net/substr
http://php.net/mktime
http://php.net/date
http://php.net/datetime.createfromformat
I'd use the DateTime class, you can create from a specific format, and then output to another.
As pointed out in the comments below, you also need to set the day to the first of the month, otherwise you'll get undesired results if the current day is greater than the number of days in the given month.
echo DateTime::createFromFormat('Ymd', 19470201)->format('F Y');
As you are passing an int to date, it is considering it as a Unix Timestamp.
To create a date object from a predefined format, use DateTime::createFromFormat.
echo DateTime::createFromFormat('Ym',198403)->format('F Y');
results in
March 1984
You'd need to add a day to it, e.g. just add "01" and then use strtotime to convert that into a unix timestamp, as the date() function expects a timestamp as the parameter.
e.g.
echo date('F Y', strtotime("19220101"));
You have text representation of dates in a non-standard format. First you have to parse them and convert them to timestamps (the number of seconds since Jan 1, 1970 00:00:00 UTC). The PHP function date() can work only with timestamps.
The best approach (as of 2017) is to use the DateTime PHP class for date & time processing:
foreach (array('197402', '192201', '184707') as $text) {
$date = DateTime::createFromFormat('Ym', $text);
echo($date->format('F Y')."\n");
}
The method DateTime::createFromFormat() parses a string using the given format and creates a new DateTime object if the parsing succeeds. It is the OOP equivalent of strtotime() but smarter (because it can get hints about what date components to search in the input string.)
The method DateTime::format() produces the text representation of a date using the provided format. It is the OOP equivalent of date().
The OOP approach (the DateTime* classes) is recommended (and better than the procedural approach) because has built-in support for timezones (the procedural date-time functions lack it.)

String to Time with PHP <= 5.1.6 (DateTime::CreateFromFormat not available)?

All I need is to compare dates represented by string values in the format d.m.y (e.g. 15.07.11 for today).
strtotime unfortunatelly gives me wrong results (probably because of the format). I found a answer to my question (PHP strtotime incorrect conversion) but DateTime::CreateFromFormat is not available in my PHP version. I could not find strfptime but think the autor of the answer meant strptime. The result of strptime is a array. I was surprised that I can compare arrays but the compare result is not valid.
What would be the easiest way to compare dates in the given string format with PHP <= 5.1.6?
You could always pass the result of strptime to mktime and get a usable Unix timestamp which you can compare or feed to the DateTime objects.
<?php
$d = strptime('15.07.11', '%d.%m.%y');
$timestamp = mktime($d['tm_hour'], $d['tm_min'], $d['tm_sec'], $d['tm_mon'], $d['tm_mday'], 1900 + $d['tm_year']);
echo date("j F Y", $timestamp);
?>
The only thing to watch for is that strptime gives the year as the number of years since 1900, and mk_time just takes a year number, so I added 1900 to it.

Past textual date to days (since) PHP

Hey guys,
how does one calculate the days past since a date like the one Twitter outputs in its API
eg:
Mon Jul 12 00:27:26 +0000 2010
to XXX
Can we do it with strtotime
Thanks guys,
Dex
Compatibility note: works only for PHP >= 5.3.0
Providing that the date format does not change, you can reverse the process (i.e. reverse timestamp -> string (on Twitters servers) to timestamp) using the exact date format. Using the table on the manual page of DateTime::createFromFormat:
<?php
$str = 'Mon Jul 12 00:27:26 +0000 2010';
$oDateTime = DateTime::createFromFormat('D M d H:i:s T Y', $str);
$unix_timestamp = $oDateTime->getTimestamp();
echo $unix_timestamp;
?>
Beware: On my machine, date('d-m-Y H:i:s', $unix_timestamp) differs two hours, the machines timezone is GMT+2.
To calculate the difference between in days between two Unix timestamps, use math (a day has 86400 seconds):
echo ($unix_timestamp1 - $unix_timestamp2) / 86400;
If you've two such dates, you can use DateTime::diff as suggested in the comments by Zerocrates. You've create two DateTime instances using DateTime::createFromFormat and invoke the DateTime::diff with two arguments passed, previously created DateTime instances. The returned DateInterval instance has a d property which contains the difference in days.
The other way would be using the getTimestamp method, doing the maths from the previous example.
References:
http://php.net/manual/en/datetime.createfromformat.php
http://php.net/manual/en/datetime.gettimestamp.php
http://www.php.net/manual/en/datetime.diff.php
http://www.php.net/manual/en/class.dateinterval.php
You can do it like that (where $your_date is the string you mentioned):
$diff = (time() - strtotime($your_date)) / (24*60*60);
In your case, when I did echo $diff; the output was (at the time I posted the answer):
321.85475694444
See more details for strtotime(), time() and date().
Hope this helped you.
You might find sth here:
performing datetime related operations in PHP
or in php manual there is a lot..
http://php.net/manual/en/function.date.php

add one year to datetime with php

$data['user']['time'] = '2011-03-07 00:33:45';
how can we add 1 year to this date ?
something like $newdata = $data['user']['time'] + 1 year ?
or
$newdata = 2012-03-07 00:33:45
Thanks
Adam Ramadhan
strtotime() is the function you're looking for:
$data['user']['seal_data'] = date('Y-m-d H:i:s', strtotime('+1 year', strtotime($data['user']['time'])));
First, you have to convert the MySQL datetime to something that PHP can understand. There are two ways of doing this...
Use UNIX_TIMESTAMP() in your query to tell MySQL to return a UNIX timestamp of the datetime column.
SELECT whatever, UNIX_TIMESTAMP(myTime) AS 'myUnixTime' FROM myTable;
Use DateTime::createFromFormat to convert your string time to something PHP can understand.
$date = DateTime::createFromFormat('Y-m-d H:i:s', $data['user']['time']);
Once that is done, you can work with the time... Depending on the method you used above, you can use one of the following.
If you have a unix timestamp, you can use the following to add a year:
$inAYear = strtotime('+1 year', $data['user']['unixTime']);
If you have a DateTime object, you can use the following:
$inAYear = $date->add(new DateInterval('P1Y'));
Now, to display your date in a format that is respectable, you must tell PHP to return a string in the proper format.
If you have a unix timestamp, you can use the following:
$strTime = date('Y-m-d H:i:s', $inAYear);
If you have a DateTime object, you can use the following:
$strTime = $inAYear->format('Y-m-d H:i:s');
Alternatively, if you don't want to deal with all of that, you can simply add one year when you query.
SELECT whatever, DATE_ADD(myTime, INTERVAL 1 YEAR) AS 'inAYear' FROM myTable;
Current (2017) Practice is to use DateTime
This question is top on a google search for "php datetime add one year", but severely outdated. While most of the previous answers will work fine for most cases, the established standard is to use DateTime objects for this instead, primarily due strtotime requiring careful manipulation of timezones and DST.
TL;DR
Convert to DateTime: $date = new DateTime('2011-03-07 00:33:45', [user TZ]);
Use DateTime::modify: $date->modify('+1 year');
Format to needs.
Change the timezone with DateTime::setTimezone from the list of supported timezones: $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
Convert to string with DateTime::format: echo $date->format('Y-m-d H:i:s');
Following this pattern for manipulating dates and times will handle the worst oddities of timezone/DST/leap-time for you.
Just remember two final notes:
Life is easier with your system timezone set at UTC.
NEVER modify the system timezone outside of configuration files.
I've seen too much code that relies on date_default_timezone_set. If you're doing this, stop. Save the timezone in a variable, and pass it around your application instead, please.
More Reading
How to calculate the difference between two dates using PHP?
Convert date format yyyy-mm-dd => dd-mm-yyyy
PHP - strtotime, specify timezone
I think you could use strtotime() to do this pretty easily. Something like:
$newdata = date('c', strtotime($data['user']['time'] . ' +1 year'));
Though the 'c' format string isn't the same as your input format. You could consult date()'s docs for how to construct the correct one.
'Y-m-d H:i:s' — as Tim Cooper suggests — looks correct.
This should do the trick (not tested).
$data = "2011-03-07 00:33:45";
echo 'Original date +1 year: ' . date('Y-m-d H:i:s', strtotime(date("Y-m-d H:i:s", strtotime($data)) . " +1 year"));
First-of-all if your date format is separated by a slash (/), like '2019/12/31' then you should convert it in dash (-) format, like '2019-12-31', to do so use str_replace() function.
$string = str_replace('/', '-', '2019/12/31'); //output: 2019-12-31
To add time/day/month/year do not use strtotime() function, because it can't add a time which is beyond year 2038.
So here I would prefer to use DateTime() function.
$string = '2000-01-01';
$date = new DateTime($string);
$date->add(new DateInterval('P60Y5M2DT6H3M25S')); //60 Years 5 Months 2 Days 6 Hours 3 Minutes 25 Seconds
echo $date->format('Y-m-d H:i:s'); //output: 2060-06-03 06:03:25

php datetime object 1960 year limitation

I am trying to use php datetime object for handling dates.
Here is my code:
$date = new DateTime('01 Dec, 1969');
echo $date->format('Y-m-d');
The above code returns 2010-12-01
But If I change year from 1969 to 1945 or anything less than 1960 then the code returns incorrect year. For example:
This code:
$date = new DateTime('01 Dec, 1950');
echo $date->format('Y-m-d');
returns
2010-12-01
This is likely a bug. Consider filing it to the bugtracker.
When you change the input format to
$date = new DateTime('Dec 1st, 1950');
echo $date->format('Y-m-d');
PHP will correctly make this into
1950-12-01
See http://codepad.org/trFfB6Q1
As of PHP5.3, you can also use DateTime::createFromFormat to create a date. This would work with your original DateTime string then:
$date = DateTime::createFromFormat('d M, Y', '01 Dec, 1950');
echo $date->format('Y-m-d');
See http://codepad.viper-7.com/08kK5M
Given that this problem does not occur on my system (PHP5.3 on a windows machine)
I suggest you update to php 5.3.
There are no drawbacks and this is probably not the only bug you will run into.
I have tested different date formats('1969/12/1','01 Dec, 1969',..) and had no problems at all.
if the problem persist feel free to slap me ;)
PHP's Datetime is based on a unix timestamp which started counting from 1st of january 1970.
You cannot use DateTime to acces a date before that.

Categories