I'm trying to figure out a way how to take a string and be able to use it in a DateTime. This is an example (obviously giving an error because of incorrect parameters):
$string = sprintf('strtotime("second monday of october", mktime(0, 0, 0, 10, 1, %d))', 2014);
$date = DateTime::createFromFormat('Y-m-d', $string);
echo $date->format('Y-m-d');
The reason why I want to achieve this is to be able to have the year be determined by other factors depending where it is located in my class: meaning that $string will be created on the fly and will be used later to output a date. My question, is there an alternative to this or is it just not possible and the year must be pre-determined. Any hand would be appreciated.
If you mean you want to get second october of a dynamic year, try doing:
$my_year = 2014;
$string = strtotime(sprintf('second monday of october %d', $my_year));
and use the $string to get formatted date
Related
Assuming you have four numeric variables:
$Index=2; // 1-6, 2 is the second occurrence
$Dow=3; // 0-6, 3 is Wednesday
$Month=3; // 1-12, 3 is March
$Year=2016;
Is there a simple way to use those numbers to create or modify a DateTime object to represent that specific date? For example, with the variables above, it would be the specific date of the 2nd Wednesday in March of 2016.
I know that you can do this with strtotime or the DateTime constructor if you have it written out as a string already. There are other answers on here that deal with that.
But since we have numeric indexes, it seems stupid to create a function that converts numbers to a human readable string that then gets passed into a string parser to generate a date.
So the question is, is there a way to use strictly numeric variables with the DateTime object without having to first convert it to a human readable string to get a relative date like the 2nd(2) Wednesday(3) of March(3)?
I'm looking for something like:
$oDate = new DateTime();
$oDate->setFromWeekdayOfMonthIndex($Position,$DOWNum,$MonthNum,$Year);
UPDATE #1
Just to clarify the question a bit, this does what I want, but is a long/silly way of doing it:
$oMonthDate = new DateTime();
$oMonthDate->setDate($Year, $MonthNum, 1);
$oFormater = new NumberFormatter('en-US', NumberFormatter::SPELLOUT);
$oFormater->setTextAttribute(NumberFormatter::DEFAULT_RULESET,"%spellout-ordinal");
$String = $oFormater->format($Position).' ';
$String .= date('l', strtotime('Sunday +'.$DOW.' days')). ' of ';
$String .= $oMonthDate->format('F'). ' '.$Year;
$oFinalDate = new DateTime($String); // "second Tuesday of January 2016"
I use a radio button that gives me two variables concatenated and I need to separate them later. It gives me a time and a date in a format 11:30pm3, where 3 is the date and 11:30pm is the time. I can split it fine with my function but if the time is one digit, like 7:30pm for example, it throws things off. I can use military time but that's not what I want.Is there a way to change this so it splits the string right after character "m" so it will work for am/pm, regardless of the length of the time being 7:00am or 07:00am. Thanks in advance.
$string = $Radio; //This is the value I get
$MeetTime = substr("$string", 0, 7); //Gives me 11:30am
$MeetDay = substr("$string", 7, 2); //Gives me 2
find out where the m is and do your logic on that
if m is at 6 then its a full length one
$loc = stripos($string,"m");
if its at 5 then it's short so adjust your split
if(preg_match('~^([\\d]{1,2}:[\\d]{1,2}[ap]m)([\\d]+)$~i', trim($string), $Matches)){
var_dump($Matches); // See what this prints
}
Hope it helps.
try this:
$date = '11:30am3';
$date = explode('pm', $date);
if(count($date) <= 2){
$date = explode('am', $date[0]);
}
print_r($date);
where $date[1] is the time and $day[0] the date.
But you should use somet other format, I'd recommend timestamps.
I have tried using date("m/d/Y", strtotime("04-05-2012")) but I will get "05/04/2012" or on some other dates for example "03-30-2012" I will get "12/31/1969" (which makes sense because it it mixing up the month and day and there is no 30th month. So how should I do this? I also want to then convert the value into a UNIX time so that I can search it against MySQL db.
You can use the DateTime object and createFromFormat static method to do it :
$date = DateTime::createFromFormat('m-d-Y',"03-30-2012");
$date->format('m/d/Y');
If you know for certain that the format you start with is DD-MM-YYY when why not use a simple replace?
e.g. $newDate = str_replace('-', '/', '04-05-2012');
One way to do it would be using explode() and mktime():
$inDate = '03-30-2012';
list($m, $d, $y) = explode('-', $inDate);
$outDate = date('m/d/Y', mktime(0, 0, 0, $m, $d, $y));
This assumes the format is somehow dynamic, though. Otherwise, str_replace() is your best option, as others pointed out.
This isn't so much a date format question as a string manipulation question.
But it's still good to know that strtotime() exists.
[ghoti#pc ~]$ cat transdate.php
#!/usr/local/bin/php
<?php
$olddate = "04-05-2012"; // assuming mm-dd-YYYY
// Get the date parts into an array
$parts = explode("-", $olddate);
// Switch to YYYY-mm-dd, which will be interpreted consistently
$neworder = sprintf("%s-%s-%s", $parts[2], $parts[0], $parts[1]);
printf("New order: %s\n", $neworder);
// Set your timezone, or PHP will whine and complain
date_default_timezone_set('America/Toronto');
// Convert your reordered date to an epoch second (unix timestamp)
$epoch = strtotime($neworder);
// At a terminal, `man strftime` (or read the PHP function's docs) for details.
print "Alternate formats:\n";
printf("\t%s\n", strftime("%D", $epoch));
printf("\t%s\n", strftime("%F", $epoch));
printf("\t%s\n", strftime("%A %B %e, %Y (week %U)", $epoch));
[ghoti#pc ~]$ ./transdate.php
New order: 2012-04-05
Alternate formats:
04/05/12
2012-04-05
Thursday April 5, 2012 (week 14)
[ghoti#pc ~]$
This will work in PHP 5.1.6. Heck, it should work in PHP 4, except for date_default_timezone_set().
I have 1 text input box so user can enter a date in the following format (i don’t want to use 3 separate input boxes for the month, date and year) :
mm/dd/yyyy (could be a single digit m/d/yyyy)
or
mm-dd-yyyy (single digit m-d-yyyy)
I then want to use preg_match to check if the user entered a value according to the format above. If yes, i will extract the month, day and year (using substr) and use php function checkdate() to check for a valid date, know when it’s a leap year and prevent mistakes such as September 31...
Hopefully, i’m not missing anything...
Right now, im stuck in trying to figure out how to use preg_match to check if the user has entered a valid date according to the format indicated above
this is what i’ve came up with... ???
preg_match(d{2})(\d{2})(\d{4})
extracting the month , day and year (looks ok to me):
$date = trim($_POST['date']);
$month = substr($date, 0, 2);
$day = substr($date, 3, 2);
$year = substr($date, 6, 4);
and finally , check the date is valid (looks ok to me):
checkdate($month, $day, $year);
Thanks
You could use something like this:
if (preg_match("#^(\d{1,2})\D(\d{1,2})\D(\d{2,4})$", trim($date), $match)
and checkdate($match[2], $match[1], $match[3])) {
$timestamp = mktime(0, 0, 0, $match[2], $match[1], $match[3]);
echo "Date is valid";
} else
echo "Invalid date";
The only issue I see here is if user inputs something like 06.01.12 expecting your system to guess 2012, when checkdate will think of the year 12. You can't just add "20" at the start of the string, since another user may input something like 15.11.99 expecting a 1999 guess. This could be solved by a readonly field with javascript-based calendar, which will force correct date format, which you can then simply explode("-", $date) without using regexp.
I have a weird date format in some files I'm parsing. Here are some examples:
1954203
2012320
2010270
The first four digits are the year and the next three digits are day of year. For example, the first date is the 203rd day of 1954, or 7/22/1954.
My questions are:
What's this date format called?
Is there a pre-canned way to parse it? I don't want to reinvent the wheel here.
Edit: Sorry, I forgot to mention my language. PHP.
Try:
$oDate = DateTime::createFromFormat('Yz', 201026);
echo $oDate->format('Y-m-d');
For Java, see SimpleDateFormat. You want yyyyDDD as the format (year, then day in year).
Assuming you get it as a string in C#...
DateTime GetDate(string input)
{
int year = Int32.Parse(input.Substring(0,4));
int day = Int32.Parse(input.Substring(4,3));
return (new DateTime(year,1,1)).AddDays(day - 1);
}
(Note the -1 offset for the day number, since you are already starting at day 1)
In PHP to format the date:
echo date_parse_from_format("Yz", $date);
You can also use
DateTime::createFromFormat("YZ", $date);
or it's alias
date_create_from_format("Yz", $date)
which returns a DateTime object
Turns out what I wanted was this:
$date = '1954203';
$year = substr($date, 0, 4);
$day = substr($date, 4, 3);
$new_date = date("Y-m-d", mktime(1, 1, 1, 1, $day, $year));