dateFromString returns the wrong date - objective-c

I have the following code:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-mm-dd";
NSDate *cDate = [formatter dateFromString:thisLine];
NSLog(#"cDate '%#' thisLine '%#'", cDate, thisLine);
NSLog prints:
cDate '2011-01-10 05:07:00 +0000' thisLine '2011-07-10'
while cDate should be '2011-07-10'
Any thoughts?
Thanks

Lowercase mm is for minutes not months, month use uppercase MM:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd";
NSDate *cDate = [formatter dateFromString:thisLine];
NSLog(#"cDate '%#' thisLine '%#'", cDate, thisLine);

The NSDate description will always print the date with its own formatting, generally for the +000 time zone. You need to use the date format to get the correctly formatted date and use MM for month not mm.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"yyyy-MM-dd";
NSDate *cDate = [formatter dateFromString:thisLine];
NSLog(#"cDate '%#' thisLine '%#'", [formatter stringFromDate:cDate], thisLine);
-(NSString*)description
Discussion The representation is not guaranteed to remain
constant across different releases of the operating system. To format
a date, you should use a date formatter object instead (see
NSDateFormatter and Data Formatting Guide)

Related

How to format date 12/2/31 H, 2:21:41 AM in Objective-c?

This is what date I am getting again our current date of 2019.
12/2/31 H, 2:21:41 AM
Can anyone help me how can I parse this date to NSDate object in Objective-c?
This calendar format belongs to the Japanese Calendar.
To parse the date with NSDateFormatter you have to replace the H with Heisei and assign a Japanese Calendar instance to the date formatter.
NSString *dateString = [#"12/2/31 H, 2:21:41 AM" stringByReplacingOccurrencesOfString:#"H" withString:#"Heisei"];
NSCalendar *japanese = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierJapanese];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US#calendar=japanese"];
formatter.calendar = japanese;
formatter.dateFormat = #"MM/d/yy G, h:mm:ss a";
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"%#", date);

Convert ISO 8601 to NSDate

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

Objective-C – NSDateFormatter dateFromString ignore time

If I'm not interested in the time can I ignore it? I.e I have a date string that looks like this #"2012-12-19T14:00:00" but I'm only interested in getting the date (2012-12-19) but if I set NSDateFormatter like [dateFormatter setDateFormat:#"yyyy-MM-dd"]; it will return me a nil NSDate.
An NSDate object will always contain a time component as well, as it is representing a point in time — from this perspective one could argue the name NSDate is misleading.
You should create a date formatter for creating dates from string, set the time to the start of the day and use a second date formatter to output the date without time component.
NSString *dateString = #"2012-12-19T14:00:00";
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateStyle:NSDateFormatterShortStyle];
[outputFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [inputFormatter dateFromString:dateString];
//this will set date's time components to 00:00
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit
startDate:&date
interval:NULL
forDate:date];
NSString *outputString = [outputFormatter stringFromDate:date];
NSLog(#"%#", outputString);
results in
19.12.12
while the format — as it is chosen by styling — will be dependent of your environment locale
all date string returns 10 characters for the date, what i mean is the date of todayy will be 2012-11-19
you can easily substring the date and use it as you want:
Example :
NSString* newDate = #"";
newDate = [[NSDate date]substringToIndex:10];
the out put will be : 2012-11-19

Create a date in xcode label

First of all I want to say thanks in advance for helping me.
I want to know how can I create a date on a label using Xcode,
and the date will follow the same date like in iphone.
Thanks
Here's one simple approach
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//uncomment to get the time only
//[formatter setDateFormat:#"hh:mm a"];
//[formatter setDateFormat:#"MMM dd, YYYY"];
[formatter setDateStyle:NSDateFormatterMediumStyle];
//get the date today
NSString *dateToday = [formatter stringFromDate:[NSDate date]];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 20.0f)];
[label setText:dateToday];
[formatter release];
//then add to a view
Creating the text date is simple, but the real question is what is your data source that you want to make the date text out of?
The date can be formatted and set in label as below.
NSDate *today = [NSDate date];
NSDateFormatter *dformat = [[NSDateFormatter alloc] init];
[dformat setDateFormat:#"dd:MM:YYYY"];
myLabel.text = [dformat stringFromDate:today];
NSDateFormatter handle format of string dates.
Instances of NSDateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.
Try this and see:
// Set date format according to your string date format
// e.g.: For,
// 22-12-1996 -> #"dd-MM-yyyy"
// 22/12/1996 -> #"dd/MM/yyyy"
// 1996-12-22 03:45:20 -> #"yyyy-MM-dd HH:mm:ss"
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd/MM/yyyy";
//dateFormatter.dateFormat = #"dd-MM-yyyy";
NSDate *date = [dateFormatter dateFromString:dateString];
if(date == nil) {
correctFormat = false;
}
NSLog("Date: %#",date);
Note: Each pairs of characters in date format relates relevant date component with date instance. You can create any type of date format using date string pattern.
Here is document by Apple: Date Formatters
Date (Day): dd
Month: MM or MMM or MMMM
Year: yy or yyyy
Here is list of date formats: Date Formats
Here is solution in Swift
var today = Date()
var d_format = DateFormatter()
d_format.dateFormat = "dd:MM:yyyy"
label.text = dformat.string(from: today)

Why does time returned by [NSDate date] differ from my current time?

hi all
I am in India.And I have used the following code to get the current date.
[NSDate date]
it displaying the "2011-01-20 06:51:35 +0000" but actual time is "2011-01-20 12:21:35 +0000"
.Please tell me how to get the current date.
Thanks in advance
You need to use Date Formatter for this purpose.Below is the sample code for that.
NSDate *testDate=[NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM DD YY hh:mm"];//You can set your required format here
NSString *dt = [formatter stringFromDate:testDate];
[formatter release];
NSString *strDateTaken=dt;
Cheers
What does “actual time” mean? The current time in your time zone? Considering the time values given I’d guess that the first one is GMT and you want IST (+5:30). (See Time zones on Wikipeda.) Depends on what you want to do with the date – if you just want a formatted date and time in your current time zone, Aditya’s answer should work.
To Find Current date and difference between current date and Given date...its working code
NSDate *testDate=[NSDate date];
NSDateFormatter *formatterNew = [[NSDateFormatter alloc] init];
[formatterNew setDateFormat:#"dd-MM-yyyy HH:mm:ss "];
NSString *dt = [formatterNew stringFromDate:testDate];
NSString *strDateTaken=dt;
NSLog(#"Date=%#",strDateTaken);
[formatterNew release]; // This line can be removed if you are using ARC
NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *toDate = [tempFormatter dateFromString:strDateTaken];
NSLog(#"Current Date ==%#",toDate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *startdate = [tempFormatter1 dateFromString:#"30-08-2011 16:25:00"];
NSLog(#"Last Date ==%#",startdate);
int i = [startdate timeIntervalSince1970];
int j = [toDate timeIntervalSince1970];
double X = j-i;
int days=(int)((double)X/(3600.0*24.00));
NSLog(#" Difference :%d",days);