How can I get timestamp as NSNumber? I only need something like this: 1232885280
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
// NSTimeInterval is defined as double
NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp];
Time Intervals Since 1970
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
Time Intervals Since Now
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSinceNow];
Time Intervals Since Date
NSDateComponents* comps = [[NSDateComponents alloc]init];
comps.year = 2014;
comps.month = 3;
comps.day = 31;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* date = [calendar dateFromComponents:comps];
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSinceDate:date];
Time Intervals Since Reference Date
The Intervals between the date object and 00:00:00 UTC on 1 january 2001.
NSTimeInterval timeStamp = [[NSDate date] timeIntervalSinceReferenceDate];
Related
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
// find next date where the minutes are zero
NSDate *nextHour = [calendar nextDateAfterDate:now matchingUnit:NSCalendarUnitMinute value:0 options:NSCalendarMatchNextTime];
// get the number of seconds between now and next hour
NSDateComponents *componentsToNextHour = [calendar components:NSCalendarUnitSecond fromDate:now toDate:nextHour options:0];
//NSLog(#"%ld", componentsToNextHour.second);
NSString *dec = [NSString stringWithFormat:#"%ld", (long)componentsToNextHour.second];
In the above code, I convert the current date and time into seconds, but I am unable to convert these seconds into unixtimestamp, any ideas on how to go about this will be highly appreciated.
I'm not sure I understand your question. If you are asking for the Unix timestamp at which the next hour starts, do this:
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
// find next date where the minutes are zero
NSDate *nextHour = [calendar nextDateAfterDate:now matchingUnit:NSCalendarUnitMinute value:0 options:NSCalendarMatchNextTime];
time_t unixTimestampAtWhichNextHourStarts = (time_t)nextHour.timeIntervalSince1970;
NSLog(#"ts=%ld", (long)unixTimestampAtWhichNextHourStarts);
I want to code an alarm clock for iOS.
My code for calculating the difference between current time and alarm time:
NSDate *date = picker.date;
NSLog(#"[date description] %#",[date description]);
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"HH:mm:ss"]; //24h time format
NSString *dateString = [outputFormatter stringFromDate:picker.date];
NSLog(#"[date description] %#",dateString);
NSDate *startDate = [outputFormatter dateFromString:dateString];
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
NSDate *endDate = [dateFormatter dateFromString:resultString];
NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:startDate];
double minutes = timeDifference / 60;
double hours = minutes / 60;
double seconds = timeDifference;
...which leads to these variables:
startDate = 2000-01-01 06:45:26 +0000
endDate = 2000-01-01 22:46:36 +0000
seconds = 57670 (= 16.01944 hours).
How to get to calculate the real time difference of 28740 seconds?
Just pass timeDifference in below method. It will give you Hours,Minutes and Seconds.
- (NSString *)timeFormatted:(int)totalSeconds{
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
return hours==0 ? [NSString stringWithFormat:#"%02d:%02d", minutes, seconds] : [NSString stringWithFormat:#"%02d:%02d:%02d",hours, minutes, seconds];
}
try below code:
Get time difference in hour, minutes,seconds from NSTimeInterval:
//.......
NSTimeInterval timeDifference = [endDate timeIntervalSinceDate:startDate];
long ti = lroundf(timeInterval);
int hour = ti / 3600;
int mins = (ti % 3600) / 60;
int secs = ti % 60;
OR
Get time difference in hour, minutes,seconds from Dates:
// Get the system calendar
NSCalendar *objCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *currentTime = [[NSDate alloc] init];
NSDate *startDate = picker.date;
// Get conversion to months, days, hours, minutes
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *TimeInfo = [objCalendar components:unitFlags fromDate: currentTime toDate:startDate options:0];
NSLog(#" %dmin %dhours %ddays %dmoths ",[TimeInfo minute], [TimeInfo hour], [TimeInfo day], [TimeInfo month]);
How can I calculate the first date later than now from a date in the past by repeating a certain interval? For example:
// Date in the past
NSDate *pastDate = [NSDate my_dateWithString:#"11/09/2001"];
// Time interval
NSTimeInterval repeatInterval = 14 * 24 * 60 * 60; // 2 weeks
// Current date
NSDate *now = [NSDate date]; // 23/07/2015
// Start calculating next date ->
NSDate *nextDate = /* interval added to past date */
// Is result later than now?
// No? Calculate again
// Abracadabra
NSLog(#"nexDate = %#",nextDate); // 28/07/2015
I don't want to use iterations. I'm concerned about calculating a case like a start date one year in the past and a repeat interval of a day.
Here is my solution, but it has iterations.
NSDateComponents *twoWeeksDateComponents = [NSDateComponents new];
twoWeeksDateComponents.weekOfMonth = 2;
NSDate *date = self.picker.date;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
NSDate *nextDate = date;
NSComparisonResult result = [nextDate compare:now];
while (result == NSOrderedAscending) {
nextDate = [calendar dateByAddingComponents:kTwoWeeksDateComponents
toDate:nextDate
options:NSCalendarMatchNextTime];
result = [nextDate compare:now];
}
NSLog(#"nexDate = %#",nextDate); // 28/07/2015
You can indeed do this without iteration, using a little arithmetic instead. You're looking for the nearest multiple of some factor f strictly greater than another value n. It's a bit more complicated being a calendrical calculation, but still just arithmetic (and NSCalendar of course does all the heavy lifting for you -- e.g., leap years).
NSDate * pastDate = ...;
NSDate * now = [NSDate date];
Get your repeat interval however you like from the user and construct an NSDateComponents representing it:
NSCalendarUnit repeatUnit = NSCalendarUnitWeekOfYear;
NSUInteger repeatInterval = 2;
NSDateComponents * repeatComps = [NSDateComponents new];
[repeatComps setValue:repeatInterval forComponent:repeatUnit];
Given the repeat unit, find the amount of that unit that occurs between the two dates, as another date components object:
NSCalendar * cal = [NSCalendar currentCalendar];
NSDateComponents * deltaComps = [cal components:repeatUnit
fromDate:pastDate
toDate:now
options:0];
NSInteger deltaVal = [deltaComps valueForComponent:repeatUnit];
Now comes the arithmetical bit. Round the delta down to the nearest multiple of the repeat interval. Then adding that rounded value (using the appropriate unit) will produce a date equal to or earlier than now.
Now, as jawboxer has pointed out, for a repeatUnit of NSCalendarUnitMonth, you get unexpected results if you calculate the date using that value and afterwards add one more repeat interval (as the original version of this answer did). Instead, add one to the number of repeats immediately; then the calendar correctly handles month increments.
NSInteger repeatsJustPastNow = 1 + deltaVal - (deltaVal % repeatInterval);
NSDateComponents * toNowComps = [NSDateComponents new];
[toNowComps setValue:repeatsJustPastNow
forComponent:repeatUnit];
NSDate * nextDate;
nextDate = [cal dateByAddingComponents:toNowComps
toDate:pastDate
options:0];
Jawboxer's Swift version of this corrected code is on Github.
EDIT: As Josh pointed out this doesn't account for leap years. So this is a good example of an implementation that might seem to work over short term testing but has holes in it. It also will be off by some hours in the log as dateFromString: will compensate for timezone while the log will log it as GMT.
NSDateFormatter* format = [[NSDateFormatter alloc] init];
format.dateFormat = #"yyyy-MM-dd 'at' HH:mm";
NSDate *pastDate = [format dateFromString: #"2001-09-11 at 00:00"];
NSTimeInterval repeatInterval = 14 * 24 * 60 * 60; // 2 weeks
NSDate *nowDate = [NSDate date];
NSTimeInterval timeFromPastDate = [nowDate timeIntervalSinceDate: pastDate];
NSTimeInterval modulus = timeFromPastDate / repeatInterval;
modulus -= floor(modulus);
NSDate *nextDate = [NSDate dateWithTimeInterval: repeatInterval * (1 - modulus) sinceDate: nowDate];
NSLog(#"nexDate = %#",nextDate); // 28th/July/2015, if current date is 23rd/July/2015
I made another solution early.
NSDate *date = ...;
static NSTimeInterval k2WeeksInterval = 14 * 24 * 60 * 60.0;
NSTimeInterval timeInterval = -date.timeIntervalSinceNow;
double repeats = ceil(timeInterval / k2WeeksInterval);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [NSDateComponents new];
components.weekOfYear = repeats * 2;
NSDate *nextDate = [calendar dateByAddingComponents:components
toDate:date
options:NSCalendarMatchNextTime];
I want to compare two NSDates with NOW ([NSDate date]).
NSDate *date1 = [NSDate dateWithString:#"1982-02-12 07:00:00 +0100"];
NSDate *now = [NSDate dateWithString:#"2012-01-25 10:19:00 +0100"]; //example
NSDate *date2 = [NSDate dateWithString:#"1989-02-12 15:00:00 +0100"];
I would like to check if now is between date1 and date2. In the example above this is the case. The date component should be completely ignored, so only the time component should be compared. How could I accomplish this?
Thanks in advance!
unsigned int flags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date1];
NSDate* timeOnly = [calendar dateFromComponents:components];
This will give you a date object where everything but the hours/minutes/seconds have been reset to some common value. Then you can use the standard NSDate compare functions on them.
For reference, here is the opposite question to yours: Comparing two NSDates and ignoring the time component
You can create a date representing the start of today and add the time as components to it to get the boundary dates.
NSDate *now = [NSDate date];
NSDate *startOfToday;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&startOfToday interval:NULL forDate:now];
NSDateComponents *startComps = [[NSDateComponents alloc] init];
startComps.hour = 7;
startComps.minute = 30;
NSDateComponents *endComps = [[NSDateComponents alloc] init];
endComps.hour = 20;
NSDate *startDate = [[NSCalendar currentCalendar] dateByAddingComponents:startComps toDate:startOfToday options:0];
NSDate *endDate = [[NSCalendar currentCalendar] dateByAddingComponents:endComps toDate:startOfToday options:0];
if ([startDate timeIntervalSince1970] < [now timeIntervalSince1970] && [now timeIntervalSince1970] < [endDate timeIntervalSince1970]) {
NSLog(#"good");
}
NSDateFormatter* formatterDate = [[[NSDateFormatter alloc] init] autorelease];
formatterDate.dateStyle = NSDateFormatterMediumStyle; // whatever format you like
NSDate *first_Date = [formatterDate dateFromString:#""];
NSDate *second_Date = [formatterDate dateFromString:#""];
NSDate *todaysDate = [NSDate date];
NSTimeInterval timeIntFormFirstDate = [todaysDate timeIntervalSinceDate:First_Date];
NSTimeInterval timeIntFronLastDate = [second_Date timeIntervalSinceDate:todaysDate];
int interval1 = timeIntFormFirstDate/60;
int interval2 = timeIntFronLastDate/60;
if (interval1 >0 && interval2 >0)
{
NSLog(#"Today's date is between first and second date");
}
I am using
NSDate *date = [NSDate date];
for getting the date, but the date I get is off by 2 hours.
NSDate objects don't have time zones. They represent an absolute moment in time. However, when you ask one for its description (by printing it with NSLog(), e.g.), it has to pick a time zone. The most reasonable "default" choice is GMT. If you're not in GMT yourself, the date will seem to be incorrect, by the amount of your own offset.
You should always use an NSDateFormatter to create a string for display. The formatter's timezone should be set to yours, which is the default.
You can get your date corrected like this:
NSDate * dateGMT = [NSDate date];
NSTimeInterval secondsFromGMT = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate * correctDate = [dateGMT dateByAddingTimeInterval:secondsFromGMT];
-(NSDate *)getDateInCurrentSystemTimeZone
{
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
return destinationDate;
}