I am trying to get the current time in NSDate format. I have been able to get the Unix timestamp to work, however, when I try to convert and format using an answer I found on SO, I get a null result. Would appreciate any suggestions on what I am doing wrong.
Would also be interested in any more direct way to get the current date time in date time format i.e.... something like 2015-09-04 00:55:25 +0000
- (NSDate *) timeStampDate {
//this returns time in string format
NSString *string = [NSString stringWithFormat:#"%f",[[NSDate date] timeIntervalSince1970] * 1000];
NSLog(#"string:%#",string);//this prints fine
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMdd"];
NSDate *date = [dateFormat dateFromString:string];
NSLog(#"date%#",date);//this prints null
return date;
/* this would go in opposite direction
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY"];
string = [dateFormat stringFromDate:date];
*/
}
-(NSDate*) timeStampDate {
NSDate* currentDate = [NSDate date];
return [NSDate dateWithTimeInterval:
[[NSTimeZone defaultTimeZone] secondsFromGMTForDate: currentDate]
sinceDate: currentDate];
}
Related
This question already has answers here:
Getting date from [NSDate date] off by a few hours
(3 answers)
Closed 8 years ago.
- (void) dateConverter{
NSString *string = [NSString stringWithFormat:#"%# %#", [[self dates]objectAtIndex:0], [times objectAtIndex:0]]; // string = 01-10-2014 11:36 AM;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:string];
NSLog(#"dateFromString = %#", date); // 2014-10-01 18:36:00 +0000
NSTimeInterval timeInterval = [date timeIntervalSince1970];
NSLog(#"dateFromString = %f", timeInterval); // 1412188560.000000
}
I am converting the string to actual date object, but I am getting different behavior
string = 01-10-2014 11:36 AM
is actual value I am trying to convert but getting this
2014-10-01 18:36:00 +0000
what is wrong with it?
The problem is a display issue.
You are using the default date formatter to print the date (NSLog used the description method).
The time is displayed in UTC (GMT) and it looks like you are in timezone -0700. The time is being displayed in timezone offset 0000.
The date/time in the system is based on the GMT time, that way times can be compared across timezones and everywhere on Earth the time is the same in the system at the same time.
Use a date formatter to get the date/time in the format you want.
Example code:
NSString *dateString = #"01-10-2014 11:36 AM";
NSLog(#"dateString = %#", dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
NSLog(#"dateFromString = %#", date);
NSString *displayDate = [dateFormatter stringFromDate:date];
NSLog(#"displayDate = %#", displayDate);
Output:
dateString = 01-10-2014 11:36 AM
dateFromString = 2014-10-01 15:36:00 +0000
displayDate = 01-10-2014 11:36 AM
Note: You can supply your own date format to get exactly the format what you want.
This question already has an answer here:
NSDateFormatter and Time Zone issue?
(1 answer)
Closed 8 years ago.
-(NSTimeInterval)convertStringToDate:(NSString *) date {
NSString *dateString = date;
NSLog(#"dateString = %#", dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date1 = [[NSDate alloc] init];
date1 = [dateFormatter dateFromString:dateString];
NSLog(#"dateFromString = %#", date1);
NSString *displayDate = [dateFormatter stringFromDate:date1];
NSLog(#"displayDate = %#", displayDate);
return [date1 timeIntervalSince1970];
}
Why I am getting NSTimeInterval with wrong timezone?
You need to read up on the internal representation of NSDates. An NSDate is saved as the number seconds since midnight on 1 Jan, 1984 GMT (The Mac OS X "epoch date") . It represents an instant in time anywhere on the earth, but using a date in GMT as it's "zero date". To display it, you need to convert it to your local time zone.
NSDate has a couple of methods to convert a date to a number: timeIntervalSince1970, which converts an NSDate to the internet standard, which is the number of seconds since Midnight 1 Jan 1970 (The UNIX "epoch date"), and timeIntervalSinceReferenceDate, which converts to the number seconds since the Mac Epoch date.
If you display a date in NSLog:
NSLog(#"Date = %#", someNSDate);
It will be displayed in GMT.
Honestly, it's unclear what you're asking and my best guess is that you just don't understand the classes at play. I've annotated your code in the hope of aiding your comprehension.
Key point: NSDate does not have a time zone. It's an opaque time stamp.
-(NSTimeInterval)convertStringToDate:(NSString *) date {
// log the input string
NSString *dateString = date;
NSLog(#"dateString = %#", dateString);
// create an object that can apply a locale and a time zone in order to
// convert an NSDate to an NSString and vice versa
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
// get a date that represents exactly now, for no reason as it's about
// to be thrown away
NSDate *date1 = [[NSDate alloc] init];
// convert to the NSDate that represents the given string.
date1 = [dateFormatter dateFromString:dateString];
// log the converted date. BECAUSE NSDATE DOES NOT HAVE A TIME ZONE,
// it will arbitrarily be displayed in UTC. Because it has to be
// displayed in something
NSLog(#"dateFromString = %#", date1);
// convert date1 back into a printable date; this will again apply
// a time zone and locale
NSString *displayDate = [dateFormatter stringFromDate:date1];
NSLog(#"displayDate = %#", displayDate);
// query the date for "The interval between the date object and
// January 1, 1970 at 12:00 a.m. GMT."; return that
return [date1 timeIntervalSince1970];
}
I am trying to find out whether current date is in between two given dates or not.First I coverted the two date into current date format i.e;2014-10-02 06:45:37 +0000
NSComparisonResult result,restult2;
NSString *startDateStr=#"10/04/2014 06:03 AM";
NSDateFormatter *startdf=[[NSDateFormatter alloc] init];
[startdf setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *startDate12=[startdf dateFromString:startDateStr];
NSString *startStr=[startdf stringFromDate:startDate12];
[startdf setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *startDate1=[startdf dateFromString:startStr]; //here startDate1 is nil
NSString *endDateStr=#"10/07/2014 03:03 AM";
NSDateFormatter *enddf=[[NSDateFormatter alloc] init];
[enddf setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSDate *endDate12=[enddf dateFromString:endDateStr];
NSString *endStr=[enddf stringFromDate:endDate12];
[enddf setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *endDate1=[startdf dateFromString:endStr]; //here endDate1 is nil
NSDate *date = [NSDate date];
BOOL isBetween=[MyViewController date:date isBetweenDate:startDate1 andDate:endDate1];
if (isBetween)
{
NSLog(#"#####YES");
}
+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
if ([date compare:beginDate] == NSOrderedAscending)
return NO;
if ([date compare:endDate] == NSOrderedDescending)
return NO;
return YES;
}
Please give any suggestions where I am going wrong.
Thanks in Advance...!
You are doing stuff in your code that is pretty much not doing anything. An NSDate object has no format. It has no time zone. It has no months, days, years. It is merely a point in time. When you then convert that date to a string you need to provide a format (which is what NSDateFormatter is for).
Change your code to something like this...
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy hh:mm a"];
NSString *startDateStr = #"10/04/2014 06:03 AM";
NSDate *startDate = [dateFormatter dateFromString:startDateStr];
NSString *endDateStr = #"10/07/2014 03:03 AM";
NSDate *endDate = [dateFormatter dateFromString:endDateStr];
NSDate *date = [NSDate date];
// use a function name that matches the convention...
if ([MyViewController isDate:date betweenStartDate:startDate andEndDate:endDate])
{
NSLog(#"#####YES");
}
I think your function should be fine. Just don't mess around with the dates. Once you have them stop there and use them.
Obtain NSDate from your string and compare.
NSDate doesnt contain any format. It is just number of seconds. So you dont need to reconvert it multiple times, its error prone.
Also double check that dateFromString: method doesnt return nil.
To verify, whether a date falls into defined date range, you can use compare method or review the following code:
NSDate *now = [NSDate date];
NSDate *yesterday = [now dateByAddingTimeInterval:-1*24*60*60];
NSDate *tomorrow = [now dateByAddingTimeInterval:+1*24*60*60];
//first condition
if([now compare:yesterday] == NSOrderedDescending && [now compare:tomorrow] == NSOrderedAscending)
NSLog(#"now > yesterday and now < tomorrow");
else
NSLog(#"now is outside yesterday and tomorrow");
NSDate *weekAgo = [now dateByAddingTimeInterval:-7*24*60*60];
//second condition
if([weekAgo compare:yesterday] == NSOrderedDescending && [weekAgo compare:tomorrow] == NSOrderedAscending)
NSLog(#"weekAgo > yesterday and weekAgo < tomorrow");
else
NSLog(#"weekAgo is outside yesterday and tomorrow");
First condition results to
2014-10-02 14:45:21.791 dateTest[95595:8857503] now > yesterday and now < tomorrow
Second condition results to
2014-10-02 14:45:24.425 dateTest[95595:8857503] weekAgo is outside yesterday and tomorrow
convert both dates in milliseconds
long firstDate = [#(floor([startDate1 timeIntervalSince1970] * 1000)) longLongValue];
long secondDate = [#(floor([endDate1 timeIntervalSince1970] * 1000)) longLongValue];
and then covert also the date you want to check like this and check if that value is bigger than firstDate and smaller than `secondDate'
I have this string date:
2014-04-21T07:55:13Z
when I convert that to NSDate I have the hour like 6:55... 1 hours less. WHY?
This is the code I am using to convert:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *newDate = [dateFormatter dateFromString:dateStr];
newDate is now 2014-04-21 06:55:13 +0000 !!!???
what is wrong?
NOTE: That one hour less would make sense if the date was my local time (GMT+1) being converted to GMT. But if that Z is zero offset ( = GMT) the date is already GMT.
I don't think your code is wrong. using this code:-
NSString *dateStr = #"2014-04-21T07:55:13Z";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate *date = [dateFormat dateFromString:dateStr];
NSLog(#" date log %#",date); //2014-04-21 02:25:13 +0000 output
// Convert date object to desired output format
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
dateStr = [dateFormat stringFromDate:date];
NSLog(#"string %#",dateStr); //2014-04-21T07:55:13Z output
but NSLog of NSDATE is not output correct according to this NSDate Format outputting wrong date so your code is right.
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: for know that is current or not to actually format the date for pretty human-readable display.
NSLog(#" date is %#",[dateFormat stringFromDate:date]);
I have an issue with my date conversion, which I didn't succeed in finding a solution. This gonna makes me crazy.
So I retreive a date from a REST Web Service, under a string type and when I try to convert the date to NSDate, I lose one year.
Here is the code :
- (NSDate *)convertISOToDate:(NSString *) dateString {
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setCalendar:[NSCalendar currentCalendar]];
[formatter setDateFormat:#"YYYY-MM-dd'T'HH:mm:ssZZZ"];
[formatter setLocale:[NSLocale currentLocale]];
NSDate *date = [formatter dateFromString:dateString];
return date;
}
When I debug, I have this in input : dateString __NSCFString * #"2017-12-30T11:51:46+0100"
And on the date object : date __NSDate * 2016-12-30 11:51:46 CET 0x1dd3e950
Anyone get an idea on the question ?
Use "yyyy" instead of "YYYY". "YYYY" is weekly based year.
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZ"];
try this:
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZZ];