I am trying to get just yyyy-MM-dd HH:mm from an NSDateFormatter.
But the string spits out Historical Date: 2016-08-23 14:03:00 +0000
I do not want the seconds or the +0000.
What am I doing wrong?
int seconds = -( days * (24 * 60 * 60)); //24 hours, times 60 minutes, times 60 seconds
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString* stringFromDate = [format stringFromDate:[NSDate date]];
NSDate * pastDate = [[format dateFromString:stringFromDate] dateByAddingTimeInterval:seconds];
NSLog(#"Date: %#", pastDate);
It happens because you printing NSDate object.
NSDate object encapsulates a single point in time, it is not responsible for it's string representation.
What you really need to do, is to calculate exact date you need, and then format it into NSString.
Something like that:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *pastDate = [[NSDate date] dateByAddingTimeInterval:seconds];
NSString *yourDateInString = [dateFormatter stringFromDate:pastDate];
NSLog(#"%#", yourDateInString);
Also, it is good practice to use NSCalendar and NSCalendarComponents to manipulate with dates and calculate new dates instead of just adding time interval.
I tried your coding first
int seconds = -( 24 * (24 * 60 * 60)); //24 hours, times 60 minutes, times 60 seconds
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString* stringFromDate = [format stringFromDate:[NSDate date]];
NSDate * pastDate = [[format dateFromString:stringFromDate] dateByAddingTimeInterval:seconds];
NSLog(#"The pastDate is - %#",pastDate);
The printed result is
The pastDate is - 2016-07-31 14:30:00 +0000
NSDate gets +0000
Then I tried with string
NSString *stringDate = [format stringFromDate:pastDate];
NSLog(#"The Date is: %#", stringDate);
Now the printed result is
The Date is: 2016-07-31 20:00
String does not have +0000
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 the time difference between 2 dates. but i am getting values as -0.0000, nan, or -357683564. below is my code to find time difference. am i doing any wrong in this calculations ?
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterNoStyle;
formatter.dateFormat = #"YYYY-MM-dd HH:MM:SS ±HHMM";//MM/dd/yyyy
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[formatter setLocale:usLocale];
NSDate *intialTime= [formatter dateFromString:[NSString stringWithFormat:#"%#",[dateArray objectAtIndex:i]]];//[formatter dateFromString:#"12/11/2005"];
NSDate *presentDate = [NSDate date];
NSTimeInterval timeInterval = [presentDate timeIntervalSinceDate:intialTime];
int seconds = (int)ceil(timeInterval);
int mins = seconds / 60;
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = timeInterval / secondsInAnHour;
NSLog(#"Time interval in Mins:%d -- %.4f -- %d",mins,timeInterval,hoursBetweenDates);
In Log :
Time interval in Mins:-35791394 -- nan -- -2147483648
intialTime - (null) and presentDate - 2014-05-09 10:30:15 +0000
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
NSDate *dateToday = [NSDate date];
NSString *date = #"09-05-14"; // Put your initial date here...
[df setDateFormat:#"HH:mm:ss"];
NSString *todayString = [df stringFromDate:[NSDate date]];
NSString *todaysDateTime = [date stringByAppendingString:todayString];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *initialDate = [df dateFromString:todaysDateTime];
NSTimeInterval ti = [initialDate timeIntervalSinceDate:dateToday];
I fixed my Issue by using NSTimeZone. here was my problem.it was displaying date as their server date and my current date was not matching to timezone and not able to format it. Thanks for you all friends for helping me to find my mistake.
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"EST"];
[dateFormatter setTimeZone:gmt];
How do you convert any given date to milliseconds? For example, 2014-01-23 to timestamp conversion.
NSDate *date = [dateFormatter dateFromString:#"2014-01-23"];
NSLog(#"date=%#",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(#"interval=%f",interval);
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval];
[dateFormatter setDateFormat:#"yyyy/mm/dd "];
NSLog(#"result: %#", [dateFormatter stringFromDate:methodStart]);
Output result: 1970/30/01
Swift
Convert the current date/time to a timestamp:
// current date and time
let someDate = Date()
// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970
See also
Convert Date to Integer in Swift
Creating a Date and Time in Swift
How to get the current time as datetime
Have it a try. "mm" stands for minute while "MM" stands for month.
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:#"yyyy-MM-dd"] ;
NSDate *date = [dateFormatter dateFromString:#"2014-01-23"] ;
NSLog(#"date=%#",date) ;
NSTimeInterval interval = [date timeIntervalSince1970] ;
NSLog(#"interval=%f",interval) ;
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval] ;
[dateFormatter setDateFormat:#"yyyy/MM/dd "] ;
NSLog(#"result: %#", [dateFormatter stringFromDate:methodStart]) ;
NSTimeinterval is really a double, being seconds since a particular date (in your case, the start of 1970)
NOTE :- UNIX Timestamp format contains 13 Digits so we need a 1000 multiplication with the result.
And the timestamp must be UTC ZONE not our local Time Zone.
- (void)GetCurrentTimeStamp
{
NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
[objDateformat setDateFormat:#"yyyy-MM-dd"];
NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:#"2014-01-23"];
NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime];
long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
NSLog(#"Local Time = %#---- UTC = %# ----- TimeSatmp = %ld ---- TimeStamp = %lld",strTime,strUTCTime,unixTime,milliseconds);
}
- (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *objDate = [dateFormatter dateFromString:IN_strLocalTime];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSString *strDateTime = [dateFormatter stringFromDate:objDate];
return strDateTime;
}
[date1 timeIntervalSinceDate:date2] will return seconds from two NSDate objects.
double seconds = [date1 timeIntervalSinceDate:date2];
double milliSecondsPartOfCurrentSecond = seconds - [seconds intValue];
milliSecondsPartOfCurrentSecond
i am using the following code to convert a value of 18900 into hh:mm:ss
unfortunately the value returned doesn't seem right as it gives me 06:15:00
can anyone please advise why its going wrong
thanks
-(NSString*)setHours:(double)result
{
NSLog(#"result %0.2f",result);
NSDate *date = [NSDate dateWithTimeIntervalSince1970:result];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm:ss"];
NSString *localizedString = [formatter stringFromDate:date];
[formatter release];
return localizedString;
}
Since you have a value that is the number of seconds since midnight, you don't need a date formatter. Try this:
-(NSString*)setHours:(double)result {
int secs = result;
int h = secs / 3600;
int m = secs / 60 % 60;
int s = secs % 60;
NSString *text = [NSString stringWithFormat:#"%02d:%02d:%02d", h, m, s];
}
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
First of all, you have to convert miliseconds in to seconds by dividing miliseconds by 1000.
NSTimeInterval result= 18900/1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:result];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
NSString *formattedDate=[formatter stringFromDate:date];
NSLog(#"Formatted Date : %#",formattedDate);
It's giving you a result for your current time zone, and the time is specified in UTC. So you're an hour after GMT I suppose.
Check out this question: NSDate dateWithTimeIntervalSince1970 NOT returning GMT/UTC time