PHP: parse string in format yW into a timestamp - php

I have a string in the format yW. Year followed by the week number. I would like to get a timestamp. I am using Php 5.2.17 on Windows.
strtotime() does not seem to be working reliably. For the string '1142' it should return the first day of the 42nd week of 2011.
Any suggestions on how to do this?

Give this a go, will work on windows also...
$date = '1201';
$y = substr($date, 0, 2) + 2000;
$w = substr($date, 2);
$ts = mktime(0, 0, 0, 0, 0, $y) + ($w * 604800);
subtract 1 from week if week 1 is the first week of the year

strtotime() does not accept that particular format. However, it can work with year and week number values if they're formatted as 2011W42.
// Convert 1142 to 2011W42
$reformatted = '20'.substr_replace('1142', 'W', 2, 0);
$timestamp = strtotime($reformatted);
See Compound Formats for details on this particular format.
Another option is the setIDODate() method on the DateTime class.
sscanf('1142', '%2d%2d', $year, $week);
$date = new DateTime('#0');
$date->setISODate(2000 + $year, $week);
$timestamp = $date->format('U');

Related

Number of decimal months between two dates

How do you find the number of decimal months between two dates in php?
I tried the code below:
$date1 = '2010-01-25';
$date2 = '2010-02-20';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
$day1 = date('d', $ts1);
$day2 = date('d', $ts2);
$diff = (($year2 - $year1) * 12) + ($month2 - $month1);
but it only gives me whole months. I want with decimals. Like 1.5 months or 1.4 months.
First off use DateTime::diff to compare your dates. This will give you a DateInterval result object.
Then I would do something like this:
$months = ($interval->y * 12) + $interval->m; // Total number of whole months
$months += number_format($interval->d / 30, 1); // Add the month fraction
Working example: http://3v4l.org/f6n3r
Dividing amount of days by 30 days is an easy implementation. It is not acceptable for sensitive calculations such as invoices or other finance related stuff.
There is an awesome DateTime extension called Carbon
$start = Carbon::create(2010, 1, 25, 0, 0, 0);
$end = Carbon::create(2010, 2, 20, 0, 0, 0);
echo $start->floatDiffInMonths($end); // "0.90437788018433"
It considers amount of days in a month, leap year and other things.
Keep in mind that calculation happens including time, so if you add 24 hours to $end, then 20 Feb 2010 will also be included:
$start = Carbon::create(2010, 1, 25, 0, 0, 0);
$end = Carbon::create(2010, 2, 20, 24, 0, 0);
echo $start->floatDiffInMonths($end); // "0.94009216589862"
It also supports daylight saving times in different timezones, for that, you'll need to use floatDiffInRealMonths
try this:
function monthNb ($vStartDate,$vEndDate) // dates are of format 2013-11-27
{$vStart = strtotime($vStartDate);
$vEnd = strtotime($vEndDate);
$vDiff = abs($vEnd - $vStart); // here abs in case theres a mix in the dates
$vMonths = $vDiff / 1036800; // number of seconds in a month of 30 days
return $vMonths;}
this will give you roughly the difference in months if all months would have 30 days. It can't really get more precise since months don't all have the same number of days. you could do a custom fonction to divide by the number of seconds corresponding to the number of days in the month of the end date, but then 1,5 month ending in january would not mean the same as 1,5 months ending in april. Understand that like Marc B pointed out in his comment, this value can never be precise since months do not have the same number of days.

Get current date and time form mktime in PHP

I have a problem with find the current date from past mktime. In PHP I find the current date using date("j");. Here I need, suppose my date was in the past year like mktime(0, 0, 0, 2, 1, 2008), then here how can I find the current date of this particular past month.
Either as #octern's solution, or you can do
$day = date('j', strtotime("-2 months"));
or
$day = date('j', strtotime('-30 days'));
depending on your need.
You may also want to refer to strtotime() manual.
Try this:
$date = getdate(mktime(0, 0, 0, 2, 1, 2008));
$day = $date['mday'];
Or just:
$day = date('j', mktime(0, 0, 0, 2, 1, 2008))

convert a date in this format '031012' into a date that I can add days to

I have a date in this format 030512 (ddmmyy).
But I'm having trouble with converting this to a date usable format I can add days to.
Basically.. I extracted the date above from a text file, Now I need to be able to add a number of days to it. But I am having trouble parsing the date in this format.
Is there another way of doing this rather then something like this:
// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
$date_after = $day . "-" . $month . "-".$year;
// Now i need to add x days to this
$total_no_nights = 010; // must be this format
$days_to_add = ltrim($total_no_nights,"0"); // 10, remove leading zero
// how do i add 10 days to this date.
You can do this (php >= 5.3):
$date = DateTime::createFromFormat('dmy', '030512');
$date->modify('+1 day');
echo $date->format('Y-m-d');
http://www.php.net/manual/en/datetime.createfromformat.php
For php < 5.3 :
$dateArray = str_split('030512', 2);
$dateArray[2] += 2000;
echo date("d/m/Y", strtotime('+1 day', strtotime(implode('-', array_reverse($dateArray)))));
try this using the month/day/year you already have:
$date = "$month/$day/$year";
$change = '+10 day';
echo date("d/m/Y", strtotime($change, strtotime($date)));
Assuming the date will always be in the future (or at least after 1st Jan 2000), you're not far wrong:
// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
// dd-mm-yy is not a universal format but we can use mktime which also gives us a timestamp to use for manipulation
$date_after = mktime( 0, 0, 0, $month, $day, $year );
// Now i need to add x days to this
$total_no_nights = "010"; // must be this format
$days_to_add = intval( $total_no_nights ); // No need to use ltrim
// Here's the "magic". Again it returns a timestamp
$new_date = strtotime( "+$days_to_add days", $date_after );
Using the DateTime object would be easier but you say you're not on PHP5.3.
You can't do date manipulation with strings becase, well, they are not dates. In PHP, you can use Unix timestamps (which are actually integers...) or DateTime objects. In you case:
$timestamp = strtotime('-10 days', mktime(0, 0, 0, $month, $day, $year));
echo date('r', $timestamp);
... or:
$object = new DateTime("$year-$month-$day");
$object->modify('-10 days');
echo $object->format('r');
Also, please note that 010 is an octal number that corresponds to 8 in decimal.
using the convert function in sql the date can be obtained in appropriate format.
anter that operations can be performed in php to manipulate the date. i hope that answers your query.

How to set an specific date?

I'm trying to create an date with
$date_end = mktime(0, 0, 0, date('m'), date('d')+7, date('Y'), $date_set);
The output is today + 7 days instead of the date given + 7.
The manual says nothing about mktime() taking a date as argument.
Use strtotime("+7 days", $date_set).
$date_end = mktime(0, 0, 0, date('m', $date_set), date('d', $date_set)+7, date('Y', $date_set));
is, I believe, what you were trying to accomplish (assuming $date_set is a timestamp). Else, #Kristian's suggestion I believe is a good one.
Why are you passing a $date_set variable, and why are you using mktime if you already have the time?
Simply add 7 days: $date_end = $date_set + (7 * 86400);

php - help converting timestamp string to readable time format

I have a record called Time with the following date string: 20100902040003 in the input file.
I need some php help to convert this to something more readable such as this format: 2010-09-02 04:00:03
and would like to format it as I print out the table data.
$timestamp = "20100902040003";
echo date('Y-m-d H:i:s', strtotime($timestamp)); // output: 2010-09-02 04:00:03
If you're sure that all records in your input file have the format YYYYMMDDHHmmss, you could try to split the string yourself and then using date() in conjunction with mktime() to generate a meaningful date format.
Since your data is already in the right format, it just needs some punctuation, so you can use a regular expression, rather than the date-parsing and date-formatting functions.
$timestamp = "20100902040003";
preg_replace('/(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/',
'\1-\2-\3 \4:\5:\6', $timestamp)
yields:
2010-09-02 04:00:03
Since the timestamp is not a unix timestamp, you have to use substr()
$timestamp = "20100902040003";
$year = substr($timestamp, 0, 3);
$month = substr($timestamp, 4, 5);
$day = substr($timestamp, 6, 7);
$hour = substr($timestamp, 8, 9);
$minute = substr($timestamp, 10, 11);
$second = substr($timestamp, 12, 13);
Then you arrange that using sprintf()
$formatted_timestamp = sprintf('%s-%s-%s %s:%s:%s', $year, $month, $day, $hour, $minute, $second);

Categories