Check NSString for specific date format - ios

I have a NSString and I need to check that it is in a this specific format MM/DD/YY. I then need to convert that to a NSDate. Any help on this would be much appreciated. Sidenote - I have searched around and people suggest using RegEx, I have never used this and am unclear about it generally. Can anyone point me to a good resource/explanation.

NSString *strDate1 = #"02/09/13";
NSString *strDate2 = #"0123/234/234";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSDate *dateFormat1 = [dateFormatter dateFromString:strDate1];
NSDate *dateFormat2 = [dateFormatter dateFromString:strDate2];
NSLog(#"%#", dateFormat1); // prints 2013-09-02 00:00:00 +0000
NSLog(#"%#", dateFormat2); // prints (null)
So you will know when it's not formatted correctly if the NSDate is nil. Here's the link to the docs if you need more info: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1

Use an NSDateFormatter for both tasks. If you can convert the string to a date then it is in the correct format (and you already have the result).

I know that this is a late answer, but it is impossible to always guarantee that a string is in this particular date format.
A date formatter, a regex, or even a human can not verify certain dates, because we don't know if the user is entering "mm/DD/yy" or "DD/mm/yy". It is common in some places to enter the day of the month first, while in other areas you enter the month first. So if they enter "09/06/2013" do they mean "September 6th" or the "9th of June"?

Here is a simple function for anyone searching for a simple solution.
- (BOOL) isTheStringDate: (NSString*) theString
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:theString];
if (dateFromString !=nil) {
return true;
}
else {
return false;
}
}
You have to change the formatter below to match the formatting your date is using.
[dateFormatter setDateFormat:#"yyyy-MM-dd"];

Related

Convert JSON date into UNIX timestamp - iOS [duplicate]

I have a timestamp coming from server that looks like this:
2013-04-18T08:49:58.157+0000
I've tried removing the colons, I've tried all of these:
Converting an ISO 8601 timestamp into an NSDate: How does one deal with the UTC time offset?
Why NSDateFormatter can not parse date from ISO 8601 format
Here is where I am at:
+ (NSDate *)dateUsingStringFromAPI:(NSString *)dateString {
NSDateFormatter *dateFormatter;
dateFormatter = [[NSDateFormatter alloc] init];
//#"yyyy-MM-dd'T'HH:mm:ss'Z'" - doesn't work
//#"yyyy-MM-dd'T'HH:mm:ssZZZ" - doesn't work
//#"yyyy-MM-dd'T'HH:mm:sss" - doesn't work
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
// NSDateFormatter does not like ISO 8601 so strip the milliseconds and timezone
dateString = [dateString substringWithRange:NSMakeRange(0, [dateString length]-5)];
return [dateFormatter dateFromString:dateString];
}
One of my biggest questions is, is the date format I have above really ISO 8601? All the examples I have seen from people the formats of each are slightly different. Some have ...157-0000, others don't have anything at the end.
This works for me:
NSString *dateString = #"2013-04-18T08:49:58.157+0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
// Always use this locale when parsing fixed format date strings
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[formatter setLocale:posix];
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"date = %#", date);
There is New API from Apple! NSISO8601DateFormatter
NSString *dateSTR = #"2005-06-27T21:00:00Z";
NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
NSDate *date = [formatter dateFromString:dateSTR];
NSLog(#"%#", date);
I also have the native API, which is way cleaner... This is the implementation I got in my DateTimeManager class:
+ (NSDate *)getDateFromISO8601:(NSString *)strDate{
NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];
NSDate *date = [formatter dateFromString: strDate];
return date;
}
Just copy and paste the method, it would do the trick. Enjoy it!
The perfect and best solution that worked for me is:
let isoFormatter = ISO8601DateFormatter();
isoFormatter.formatOptions = [ISO8601DateFormatter.Options.withColonSeparatorInTime,
ISO8601DateFormatter.Options.withFractionalSeconds,
ISO8601DateFormatter.Options.withFullDate,
ISO8601DateFormatter.Options.withFullTime,
ISO8601DateFormatter.Options.withTimeZone]
let date = isoFormatter.date(from: dateStr);
For further more detail, you can refer to apple's official documentation: https://developer.apple.com/documentation/foundation/nsiso8601dateformatter

How do I NSLog an NSDate?

With the code pasted below, I am trying to log an NSDate. What am I doing wrong here?
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd"];
NSDate *todaysDate;
todaysDate = [NSDate date];
NSLog(#"Todays date is %#",formatter);
All you have to do is:
NSLog(#"Todays date is %#",[formatter stringFromDate:todaysDate]);
What you are doing wrong is you haven't done anything to associate the date with the formatter. So, you would want to do something like this:
NSLog(#"Todays date is %#", [formatter stringFromDate:todaysDate];
The NSDate doesn't know anything about formatting (just date information), and the NSDateFormatter doesnt really know anything about dates, just how to format them. So you have to use methods like -stringFromDate: to actually format the date for pretty human-readable display.
If what you need is to just see the date information and don't need a particular format, you don't need a formatter to log a date:
NSLog(#"Todays date is %#", todaysDate);
Will work fine to give you the -description of the NSDate object. I wouldn't use this for anything you display to the user (do use an NSDateFormatter for that), but this is handy if you're just debugging and need to see information about an NSDate object.
Complete example:
NSDate *today = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd"];
NSLog(#"%#",[formatter stringFromDate:today]);
[formatter release];

NSLog showing the previous Date

I want to retrieve all the entries from core data added between two dates.I am using NSPredicate. As I am not getting the correct result I tried logging the date.It is showing the previous dates.After googling for a while I added
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; to my code.Now,Its showing correct dates but the results are still wrong.
This is the code I used.
NSDate *fromDate = [[self dateFormatter]dateFromString:self.fromDateField.text];
NSLog(#"%#",fromDate);
NSDate *toDate = [[self dateFormatter]dateFromString:self.toDateField.text];
NSLog(#"%#",toDate);
NSComparisonResult result = [fromDate compare:toDate];
switch (result) {
case NSOrderedAscending:
{
//code
}
- (NSDateFormatter *)dateFormatter
{
static NSDateFormatter *dateFormatter = nil;
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
}
return dateFormatter;
}
Thanks in advance
If you log an NSDate object directly it will always display the tome in GMT/UTC timezone. you have to log the output of a date formatter.
NSLog(#"%#",[self.dateFormatter stringFromDate:toDate]);
This will take your timezone in account. Or better: the timezone of the dateformatter's calendar — what is the device default if you dont change that.

NSDateFormatter won't format strange date string

So I have a date string I receive that looks like this: "2013-03-20T21:13:26-7:00" that I receive from a web back end. I have no control over the back end, just a fyi.
My preference would be to have the date formatted like this: 9:13pm at 3/20.
When I do the following
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date = [dateFormatter dateFromString:#"2013-03-20T21:13:26-7:00"];
date is null.
My first thought is that the date string looks odd, and maybe I should remove the T and the "-7:00", as the "-7:00" is appended to every date I receive, and I'm not sure what it is for.
Even after the string looks like #"2013-03-20 21:13:26", date is still null.
I will admit I am not a pro at formatting dates, so if I could get some help with this issue, that would be great.
Thanks in advance!
You have to set dateFormat to the dateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssz"];
NSDate *date = [dateFormatter dateFromString:#"2013-03-20T21:13:26-7:00"];
[dateFormatter setDateFormat:#"hh:mma 'at' MM/yy"];
NSString *dateString = [dateFormatter stringFromDate:date];
Set the date format for the dateFormatter, your problem lies in the last part of the date, secondly you can set the T in the dateformatter as follows
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssz"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSDate *date = [dateFormatter dateFromString:#"2013-03-20T21:13:26-7:00"];
Set dateFormat,
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];

Converting NSString to Date

I have two strings: date1 = 3-3-2011;
and i want to convert in to 3-March-2011 and display it in label.
NSString *myString = 3-3-2011;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"d-MM-YYYY"];
NSDate *yourDate = [dateFormatter dateFromString:myString];
//now format this date to whatever you need…
[dateFormatter setDateFormat:#"d-MMM-YYYY"];
NSString *resultString = [dateFormatter stringFromDate:yourDate];
[dateFormatter release];
but yourdate = 2010-12-25 18:30:00 +0000
resultstring = 26-Dec-2010
i want 3-March-2010
please help!
Thank you.
You can use NSDateFormatter.
Convert your current string to NSDate object, so that you can
convert it into any format you want.
NSString *myString = #"3-3-2011";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"d-M-yyy"];
NSDate *yourDate = [dateFormatter dateFromString:myString];
Now you can convert this NSDate to any format you want.
[dateFormatter setDateFormat:#"d-MMMM-yyyy"];
NSString *resultString = [dateFormatter stringFromDate:yourDate];
[dateFormatter release];
Apple's documentation on NSDateFormatter is here.
Take a look at NSDateFormatter. In particular, take a look at the dateFromString: and stringFromDate: methods. You'll need to convert your original string to an NSDate, then convert that NSDate to another string.
One tip for using NSDateFormatter: be sure always to set a locale. If you don't manually set a locale, it has a bug regarding 12/24 hour clock settings. The example code on the page I linked to shows how to set a locale.
Use d-M-Y (or M-d-Y, depending on which is the month):
NSString *myString = 3-3-2011;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"d-M-Y"];
NSDate *yourDate = [dateFormatter dateFromString:myString];
And see the Unicode standard referred to in the Apple docs.

Resources