EDT 13:28 CEST 19:28 KST 02:28

Streams: 133 live
91478 total viewers

Active: 9443
[SPL] Round 5 Week 3 Previ…
Presenting Store 2.0
[WCS EU] Ro16 - Group D Pr…
[GSTL] Week 9 - Things Tha…
[WCS KR] Code S Ro8 - Day …
Axiom.Miya Retires
This Week in Starcraft 2: …
TargA joins Team Dignitas
Invites and Qualifiers for…
[SPL] Round 5 Week 3 Start…
EG and mousesports Advance…
RaidCall D2L Launches Seas…
tradimo - $36,000 stock pi…
TL Advertising Features
Taiwan Philippines incid…
[TV/BOOK] *SPOILERS* Gam…
[TV] HBO Game of Thrones
[game]Boobs, butt or sho…
Daft Punk: Random Access…
The Team Liquid Book Club
IB Programme
Presenting Store 2.0
TL.net Ten Commandments
The Automated Ban List
Dragon Fan Club
The Axiom Manor
[Stream] Cb_RaZeR from Gol…
[Stream] Pro7ecT
Computer Build Resource Th…
[G] Streaming with OBS (Op…
OBS stream ~90fps but spik…
The Ultimate Mouse Thread
2 screens only one works
What's in the future for…
Code S Group of Death, P…
Awesome/Confusing SC2 BM
Evil Geniuses Releases G…
Pilot Episode - Nesteeeeea
[H] TvP Stopping 2 base …
[SHOUTcraft AM] Ro8 - May …
[SPL] KT Rolster vs. EG-TL…
GIGABYTE Pro League 2013 -…
[Showmatch] Team .SCA vs m…
BelleNOiR's Followers Tour…
The HotS Zerg Help Me Thread
Starcraft moving towards l…
The HotS Terran Help Me Th…
[G] TheCore - Advanced Key…
[L][D]HotS Terran Mech Res…
[M] (2) Artesia Prospect
[A] Starbow
Competitive Battlecraft wi…
Map Jam & Challenge #5
[M] Bio Chamber
TL's Item Trading Thread.
General Discussion
Dota 2 QQ thread
EG and mousesports Advan…
Invites and Qualifiers f…
[Stream] Rhyme - Very Hi…
[The International] Wester…
Perfect World's Dota 2 Su…
The Premier League Season 5
Tt eSPORTS Dota 2 Weekly #…
Curse DOTA2 Invitational
Simple Questions, Simple A…
Solo Mid - Who? What? How?
Drum of endurance, why?
What supports & why ?
[Guide] Mechromancer's Gui…
iCCup Attack Episode 5 "…
[TLS2] Qualifiers - Lega…
SC2 Player looking to le…
Few Mirrors when Both Pl…
[G] Streaming BW on Just…
Map (4)Kyanite Prospect …
[TLS2] Qualifier #3
[TLS2] Qualifier #2
Gambit's Cup Season 3 Roun…
[R&S] Gambit's Cup Season …
C Ranks Teamleague Season 1
Simple Questions, Simple A…
Tips and tricks: Defilers …
Practice Partner Thread
Challenger map on Starcraf…
World of Tanks
Ice Hockey World Champio…
Rome II Announced
TL MMA Pick'em Pool 2013
2012 - 2013 Football Thr…
[Patch 3.07: Nerf Everythi…
[LoL] [SFW] Random Pics & …
The Shikyo Memorial for QQ…
[OGN] Olympus The Champion…
[LPL] Tencent LoL ProLeagu…
[LoL] General Stream Thread
[TL R&D] T.R.O.L.L.S.
Simple Questions, Simple A…
[Champion] Nunu
Witch Doctor Discussion
D3 Hardcore Community
[Stream] Pokebunny - Hardc…
[M][N] Les Mafia
Doctor Who Mafia
Les Mafia Voting Thread
The Injuries Thread
TL Health and Fitness Init…
Running Thread
Leta - Movie
Michael - skyline
Anytime - Beast
By.Hero - Shuttle
Anytime - Pusan

Website Feedback

Closed Threads

IRC Chat
irc.quakenet.org #teamliquid

IRC Web Client

TeamSpeak 3 (68 users)

PHP - Date Format Check

Forum Index > Blogs 1 2 All
  tofucake   United States. July 21 2010 01:15. Posts 11370Profile Blog # 
I needed to make sure dates were in Y-m-d format for some calculations at work, so I wrote this up. It's not perfect, but it's quite enough to handle my needs. So, for anyone who uses PHP and needs to make sure dates are in Y-m-d format (for strtotime() or whatever reason), I grant you checkDateFormat(). It checks for valid formatted dates with space, hyphen, period, or slash separation.

function checkDateFormat($date, $empty = '0', $sep = '/')
{
$date = preg_replace('/[^\d\-\. \/]/', '', $date); // remove non-numeric and non-date separaters

$check = preg_split('/[ \-\.\/]/', $date);
if(empty($check)) return '0';

foreach($check as &$item)
$item = str_pad($item, 2, '0', STR_PAD_LEFT);
$date = implode('-', $check);

// matches for all format dates, with space, hyphen, period, or slash separators
// correct format needed is Y-m-d
// 100 is used as the final check to keep room open for later additions
$patterns = array(
0 => '/(9999)[- \.\/](09)[- \.\/](09)/', // one of the many different "blank" values used
1 => '/(0[1-9]|1[012])[- \.\/](0[1-9]|1[012])[- \.\/](\d{4,4})/', // unknown d-m order, Y at end
2 => '/(\d{4,4})[- \.\/](0[1-9]|1[012])[- \.\/](0[1-9]|1[012])/', // unknown d-m order, Y at front
3 => '/(0[1-9]|1[012])[- \.\/](0[1-9]|[12][0-9]|3[01])[- \.\/](\d{4,4})/', // m-d-Y
4 => '/(\d{4,4})[- \.\/](0[1-9]|1[012])[- \.\/](0[1-9]|[12][0-9]|3[01])/', // Y-m-d (aka already correct)
5 => '/(0[1-9]|[12][0-9]|3[01])[- \.\/](0[1-9]|1[012])[- \.\/](\d{4,4})/', // d-m-Y
6 => '/(\d{4,4})[- \.\/](0[1-9]|[12][0-9]|3[01])[- \.\/](0[1-9]|1[012])/', // Y-d-m
99 => '/ |[s(\302\240|\240)]+|[W]+/', // blank, empty, or placeholder
100 => '/(\d{2,2})[- \.\/](\d{2,2})[- \.\/](\d{2,2})/' // unknown all double digits
);

// for unknown d-m order assume month is first
$replace = array(
0 => $empty,
1 => "$3{$sep}$1{$sep}$2", // unknown d-m order, Y at end -> Y-m-d
2 => "$1{$sep}$2{$sep}$3", // unknown d-m order, Y at front -> Y-m-d
3 => "$3{$sep}$1{$sep}$2", // m-d-Y -> Y-m-d
4 => "$1{$sep}$2{$sep}$3", // Y-m-d -> Y-m-d
5 => "$3{$sep}$2{$sep}$1", // d-m-Y -> Y-m-d
6 => "$3{$sep}$1{$sep}$2", // Y-d-m -> Y-m-d
99 => "$0",
100 => $empty
);

foreach($patterns as $index => $pattern)
if(preg_match($pattern, $date))
return preg_replace($pattern, $replace[$index], $date);

return $empty;
}


Yeah, the regular expressions are long, but whatever. I replaced tabs with 2 spaces because it was huge (I develop with tabstop = 4, but the most common setting is 8, which is ugly).

if you want to return the original date, change $replace as follows:
100 => "$1-$2-$3"

Easy, eh?

I'll explain it more thoroughly later (ie: when I'm not at work) if anyone wants me to.

[update]
Added in checks for single digits (again, my users cannot be trusted!) and some other checks
Last edit: 2010-07-23 23:31:29


kwark > i will mentor you if you wish, but i'm like the absent drunk father you never wanted
Old Post

  Dance.jhu   United States. July 21 2010 01:46. Posts 292Profile Blog # 
Yea, that looks right......
It is what it is...
Old Post

 
 Cambium   Japan. July 21 2010 01:50. Posts 15607
Profile Blog # 
More like "Regex - Date Format Check"
When you want something, all the universe conspires in helping you to achieve it.
Old Post

 
 gen.Sun   United States. July 21 2010 02:00. Posts 502
Profile Blog # 
stackoverflow.com
Old Post

  tofucake   United States. July 21 2010 02:38. Posts 11370Profile Blog # 

On July 21 2010 01:46 Dance.jhu wrote:
Yea, that looks right......

^^


On July 21 2010 01:50 Cambium wrote:
More like "Regex - Date Format Check"

Nah. Regex is a way of expressing patterns, you still need Perl/PHP/somelanguagethathandlesregex to use them. But yeah, it's more regex than PHP :X



On July 21 2010 02:00 gen.Sun wrote:
stackoverflow.com

Is that a nice way of saying "gtfo"?
Last edit: 2010-07-21 02:39:13
kwark > i will mentor you if you wish, but i'm like the absent drunk father you never wanted
Old Post

 
 Louder   United States. July 21 2010 03:59. Posts 2276
Profile Blog # 
What is the context of this solution - where's the data coming from? If you can't assume users are entering dates in just one format, then you can't assume they're not going to put the day the day before the month in all ambiguous dates. The clear problem here is the lack of disambiguation with m-d/d-m dates.
http://www.gosucoaching.com - Starcraft:Broodwar and Starcraft 2 Lessons and Training Resources
Old Post

  tofucake   United States. July 21 2010 04:06. Posts 11370Profile Blog # 
True, but the data is coming from America (not really what you asked, but eh?), so dates are typically m-d-Y.

As for who's entering it, right now there's only a few people in our office, but this project will be sold to others. My code (elsewhere) checks the whole ambiguous date thing in other ways.
kwark > i will mentor you if you wish, but i'm like the absent drunk father you never wanted
Old Post

 
 Pryce   Canada. July 21 2010 04:58. Posts 7
Profile # 
There's not really a need for such complicated logic. strtotime accepts any english date format so you could use something like:

$time = strtotime($date);
if ($time < 0) throw new Exception("Invalid Date Format: $date");
return date('Y-m-d', $time);

If you're running PHP 5.2 or newer, you can also use the DateTime class.
return new DateTime($date); // throws an exception if your date is invalid
Last edit: 2010-07-21 05:05:31
Old Post

  R1CH       Administrator       July 21 2010 05:04.Profile Blog # 
I don't see why checkdate() wouldn't work for this if you expect the arguments in a certain order. This seems like more of an input problem than a parsing problem.
Twitter: @R1CH_TL
Old Post

 
 Louder   United States. July 21 2010 08:42. Posts 2276
Profile Blog # 
The dates are presumably in text... only reason you would do this
http://www.gosucoaching.com - Starcraft:Broodwar and Starcraft 2 Lessons and Training Resources
Old Post

 
 gen.Sun   United States. July 21 2010 10:14. Posts 502
Profile Blog # 

On July 21 2010 02:38 tofucake wrote:

Show nested quote +


Is that a nice way of saying "gtfo"?


It's just a better place to ask programming questions, it'll be both faster and better.
Old Post

 
 aers  *   United States. July 21 2010 11:18. Posts 1083
Profile # 
He's not asking a question, though.
Old Post

  tofucake   United States. July 21 2010 21:02. Posts 11370Profile Blog # 

On July 21 2010 04:58 Pryce wrote:
There's not really a need for such complicated logic. strtotime accepts any english date format so you could use something like:

$time = strtotime($date);
if ($time < 0) throw new Exception("Invalid Date Format: $date");
return date('Y-m-d', $time);

If you're running PHP 5.2 or newer, you can also use the DateTime class.
return new DateTime($date); // throws an exception if your date is invalid

strtotime() is used, but it doesn't accept any format. This is used for financial transactions (well, displaying them..thousands of them), so a bunch of "Invalid Date Format: $date" displays is not acceptable.



On July 21 2010 05:04 R1CH wrote:
I don't see why checkdate() wouldn't work for this if you expect the arguments in a certain order. This seems like more of an input problem than a parsing problem.

The people inputting the dates cannot be trusted.



On July 21 2010 10:14 gen.Sun wrote:

Show nested quote +



It's just a better place to ask programming questions, it'll be both faster and better.

I'm not asking a question, I'm posting a solution to a possible question. Also, I literally just forgot what I was going to say.
kwark > i will mentor you if you wish, but i'm like the absent drunk father you never wanted
Old Post

 
 Louder   United States. July 22 2010 01:49. Posts 2276
Profile Blog # 

On July 21 2010 21:02 tofucake wrote:

Show nested quote +


strtotime() is used, but it doesn't accept any format. This is used for financial transactions (well, displaying them..thousands of them), so a bunch of "Invalid Date Format: $date" displays is not acceptable.



See, I just assumed that you were working with large blocks of text, because otherwise regular expressions are one of the worst ways to solve this problem. strtotime() will work with any of the date formats you test for, and will make the same assumption your code does for ambiguous month/day formats. But whatever floats your boat.
http://www.gosucoaching.com - Starcraft:Broodwar and Starcraft 2 Lessons and Training Resources
Old Post

  tofucake   United States. July 22 2010 04:55. Posts 11370Profile Blog # 
Yeah I was using just strtotime() before, and it was returning 0 for about half the dates. When I started using my version, all the dates are formatted correctly (and all the calculations are correct).
kwark > i will mentor you if you wish, but i'm like the absent drunk father you never wanted
Old Post

  tofucake   United States. July 23 2010 23:32. Posts 11370Profile Blog # 
Shameless bump! I updated my original with a few more checks. Works better since I found some more formats in the database :|
kwark > i will mentor you if you wish, but i'm like the absent drunk father you never wanted
Old Post

 
 konadora  *   Singapore. July 23 2010 23:43. Posts 44465
Profile Blog # 
php looks hard ;;
OPPAI GUNDAM STYLE
Old Post

  tofucake   United States. July 24 2010 01:06. Posts 11370Profile Blog # 
It's really not. Most of that is actually Perl (which is very difficult to read if you're not used to it). The only reason I do something this complicated is because I didn't write the original stuff, and that allowed for (and does) a lot of dumb things.
kwark > i will mentor you if you wish, but i'm like the absent drunk father you never wanted
Old Post

 
 Dycedarg   United States. July 24 2010 03:16. Posts 12
Profile # 
Is this for users to enter dates into a text box and then you check it? If so why go through this if you can just restrict the users from using text boxes and just have drop down boxes or a calendar of some sort. That way you never need to worry about bad user inputs. Its usually better to just not allow users the freedom to do anything they want because they can and WILL break it.
Old Post

  tofucake   United States. July 24 2010 03:19. Posts 11370Profile Blog # 
Because there are already thousands upon thousands of dates in the database. I didn't write the original site, I've come in to fix it.
kwark > i will mentor you if you wish, but i'm like the absent drunk father you never wanted
Old Post

1 2 All
Please log in or register to reply.
 
Refresh
 << May '13 >> 
Mo Tu We Th Fr Sa Su
  12345
6789101112
13141516171819
20212223242526
2728293031  
FEATURED ON AIR:
[TI3] Playoff - West…
ON AIR:
[URTL] Atlas vs SCS
Gigabyte PL Hyun vs…
Followers #8
AWGL
Upcoming events:  [ More ]
33mSHOUTcraft America…
1h 33mGN 1v1 Tournament
1h 33m.SCA vs mYi
1h 33m[URTL] Imper vs eX…
1h 33mTLS2 Qualifier #3…
Refresh
StarCraft: Brood War
StarCraft 2
Dota 2
Other Notable Streams
[ Show 107 non-featured ]

» Recent SC2 Results
» Premier SC2 Tournaments
Sidebar Settings...

The Little App Factory



The opinions expressed by our users do not reflect the official position of TeamLiquid.net or its staff.

Advertising | Jobs | Privacy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren. Ad tag: TF_US.
The contents of this webpage are copyright © 2002-2013 Teamliquid.net. All Rights Reserved