objective c - Check if string is in format dd.mm.yyyy -
i wanna check if string in format dd.mm.yyyy, like
if(mystring in format dd.mm.yyyy) { nslog(@"ok"); } else{ nslog(@"no");
you can use code this:
nsstring *datestring = @"01.01.1970"; nsdateformatter *dateformatter = [[nsdateformatter alloc] init]; dateformatter.dateformat = @"dd.mm.yyyy"; if ([dateformatter datefromstring:datestring]) { //yes } why nsdateformatter: created parse dates. plus, way easy way change date format , side effect, valid nsdate object can work with.
however, if intending use dateformatter (for instance, used inside uitableviewcell), might encounter performance issues. if did, , you're sure nsdateformatter causing (instruments might here), reuse dateformatter. example, so:
nsstring *datestring = @"01.01.1970"; static nsdateformatter *dateformatter = nil; static dispatch_once_t oncetoken; dispatch_once(&oncetoken, ^{ dateformatter = [[nsdateformatter alloc] init]; dateformatter.dateformat = @"dd.mm.yyyy"; }); if ([dateformatter datefromstring:datestring]) { //yes } it seems (it guess based on tests ran) first call datefromstring triggers lazy initialization inside dateformatter, , takes time (several tests results below). if reuse it, nsdateformatter initialization performed once.
on iphone 5s ios 8.4.1 dispatch_once version works 10 times faster:
dispatch_once: 0.536 seconds, recreation: 5.475 seconds (time parse 10.000 dates)
in same test @zaph got 2x performance difference on iphone 6s ios 9.x:
dispatch_once: 0.57 seconds, recreation: 1.01 seconds (time parse 10.000 dates)
so, depends on device, os version , on how intensively you're going use dateformatter. in cases second code fragment might overkill. encountered situations provided noticeable performance boost.
Comments
Post a Comment