FAQ Database Discussion Community


Detect when it is evening/night - NSDate - iOS

ios,objective-c,time,nsdate,nscalendar
I have an iOS app. One of the sections of the app shows a simple little weather forecast for a specific location. As part of this forecast, the app also shows some images. The images are either day based, in which case they will have a 'sun' image or night...

Using NSTimeInterval after using dateFromString

swift,date,nsdate,nsdateformatter,nstimeinterval
I am working in swift and I am having trouble with NSDateFormatter and NSTimeInterval. What I am trying to do is save a string representation of a date, then later convert it back to an NSDate object and then find the time interval between that date and the current time....

How to get the hour from the current time? [duplicate]

ios,objective-c,nsdate,nsdatecomponents
This question already has an answer here: How do I get the current hour using Cocoa? 5 answers Is there any code like that: - (IBAction)Go:(id)sender { if(current time is between 00:01 AM to 9:00 AM) {do something} else if(current time is between 3:00 PM to 9:00 PM) {do...

Objective C - Generate an array of time objects with an interval of X mins?

objective-c,arrays,time,nsdate
I would like to create an array of time objects in 24-hour clock which have an interval of X mins between each one; and should validate as NSDate/NSTime objects. ie: Generated output 00:00, 00:30, 01:00, 01:30, etc I'd like the time objects to be validatable against NSDates. I'm thinking that...

Get the first day of week without WeekCalendarUnit

swift,nsdate
I would like to get the first day of the week depending on a NSDate. It works fine but I have a warning because WeekCalendarUnit is deprecated. I made some research and I tried to replace WeekCalendarUnit with : static var CalendarUnitWeekday: NSCalendarUnit { get } static var CalendarUnitWeekdayOrdinal: NSCalendarUnit...

SWIFT : Convert String from XLM to NSDate

ios,swift,nsstring,nsdate,nsdateformatter
The following code works on the simulator but doesn't on devices. I tried to replace Z with xx with no luck. Any help appreciated. Thanks. func convertDateStringToNSDate(dateString: String) -> NSDate { var dateFormatter = NSDateFormatter() // Sat, 20 Jun 2015 16:50:20 +0200 dateFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss xx"...

Sorting table sections by NSDate

ios,objective-c,uitableview,nsdate
How do I sort NSDate so that if a time on a date is 05:00 Sunday morning, it stays on Saturday "night", but last on the list? I sort my tableview sections by date from JSON data [[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"fodboldStream", @"command", nil] onCompletion:^(NSDictionary *json) { //got stream //NSLog(@"%@",json); [[API...

NSDateFormatter to Int in Swift

swift,int,nsdate
I am trying to convert a NSDateFormater Int, but the variables return nil. This is the code I'm using: var datePeriodBegin:NSDate = NSDate() if(NSUserDefaults.standardUserDefaults().objectForKey("datePeriodBegin") != nil){ datePeriodBegin = (NSUserDefaults.standardUserDefaults().objectForKey("datePeriodBegin")! as? NSDate)! } let datePeriodEnd = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitMonth, value: 6, toDate: datePeriodBegin, options: nil)! var dateFormatter: NSDateFormatter = NSDateFormatter()...

how to add Hours to date in swift in this format “2015-06-11T00:00:00.000Z” as in one string while parsing in SWIFT

ios,iphone,swift,date,nsdate
How to add Hours to date in swift in this format "2015-06-11T00:00:00.000Z" as in one string while parsing in SWIFT. I was trying to add time to date in ons string for parsing in SWIFT. I have two texfields representing date and time from the date picker, but when I...

Format NSDate to this format in NSString:- January 15 2013

ios,objective-c,iphone,nsdate,nsdateformatter
Currently , I am storing the dates in a NSArray, as I have to load the list of dates in custom drop down view, but can't able to do so because of the following issue. Here is the code how I am trying to format the NSDate:- NSCalendar *currentCalendar =...

Check whether NSDate is Monday/Tues/etc

ios,objective-c,cocoa-touch,date,nsdate
I have an iOS app which needs to set a few different date labels according to the current day. I am using NSDate and NSDateFormatter to do this. However there is something I am not sure about: if the user has an iOS device with their language/localisation set to something...

Testing for daylight saving time within Cocoa and CocoaTouch

objective-c,cocoa,unit-testing,nsdate
I am developing a calendar application that needs to draw rectangles whose heights and vertical position are based on the start date of the event they represent. I am trying to test the layout system against dates and time zones with daylight saving. Specifically I want to account for the...

Strange date when using dateformatter transfer a nsstring to nsdate

ios,nsdate
Then code is below: NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"]; NSDate *date=[dateFormatter dateFromString:@"2015-4-23 10:08"]; NSLog(@"%@",date); and the log is : 2015-05-17 23:24:58.244 test[25628:871758] 2015-04-23 02:08:00 +0000 why the nssting is 10:08,the date is 02:08? Thank you....

NSDateComponents doesn't return date

ios,swift,nsdate,nscalendar,nsdatecomponents
I am trying to get data from 2 variables: hours = "08" and minutes = 30. I am doing it this way: let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) let components = NSDateComponents() components.hour = hours.toInt()! components.minute = minutes.toInt()! let neededDate = components.date But neededDate is nil. Maybe I'm doing something wrong?...

Swift - Converting JSON date to Swift compatible date

javascript,json,swift,date,nsdate
I am trying to convert a date in which the javascript code is generating the current date using the Date() function. But when I print it out, I am getting nil. my code: let date2 = data?[0] as! String println(date2) var str = "2013-07-21T19:32:00Z" var dateFor: NSDateFormatter = NSDateFormatter() dateFor.dateFormat...

Convert a mysql date to NSDate then check how many days between

swift,cocoa,date,nsdate
I'm having problems with NSDate in Swift. I JSON a date formatted in Y-m-d from my database. This is stored as a string called survey_date I then convert the string to a NSDate using dateFormatter I want to work out the amount of days between the survey_date and NOW Error...

Creating NSDate from components without “timezone correction”

ios,swift,nsdate,nscalendar,nsdatecomponents
I have a function func createDate(day: Int, month: Int, year: Int) -> NSDate { var comp = NSDateComponents() comp.day = day comp.month = month comp.year = year var cal = NSCalendar.currentCalendar() if var date = cal.dateFromComponents(comp) { return date } return NSDate() } If I call it with createDate(07, 01,...

Find days between two dates in each Quarter

ios,iphone,sqlite,nsdate,nsdatecomponents
I have two date columns in table (SQLITE) Now what i need is to find number days appear in each quarter between these two dates For example let's say, start_Date = 12-Jan-2015 end_Date = 13-Jul-2015 So result should be like: Quarter 1 = 79 days Quarter 2 = 91 days...

Check if time of NSDate object has passed

ios,nsdate,nsdateformatter
Im trying to check if the time of an NSDate has passed. Ive used the following but that obviously has the year so therefore it has passed. How would I check just the time of the NSDate object, only Hour and minutes are important: NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];...

NSDate value is always returned in my time zone

objective-c,nsdate,nsdateformatter
TL/DR: I need an NSDate representing 1970-01-01 00:00:00 +0000 specifically. Using [NSDate dateWithTimeIntervalSince1970:0] returns the date adjusted for my time zone. I can't figure out how to fix this. I am attempting to write an Objective-C iOS test that revolves around NSDates. The trouble is, any NSDate object I try...

NSDate without timezone for a UIDatePicker

ios,objective-c,nsdate,uidatepicker
I have a UIDatePicker which I'm using to choose the opening time of a shop. The problem is that the date picker is changing the displayed time depending on the timezone, but I just want to show the time exactly as it appears in the NSDate. For example, my NSDate...

NSDateFormatter returning null when trying to fetch date from string

ios,objective-c,nsdate,nsdateformatter
I am trying to get date from string. But it's returning null value. Can anyone tell the reason? I think date formatter is incorrect. Below is the code: NSString *dateString = @"2015-02-28 05:50:15"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-dd-MM HH:mm:ss"]; NSDate *dateFromString = [dateFormatter dateFromString:dateString]; NSLog(@"date: %@", dateFromString);...

Compare dates from given array and two date ranges swift

swift,cocoa-touch,xcode6,compare,nsdate
Hi i have a problem scenario with date comparison with given date range the scenario is as follows: i have an array containing data: var filter1Date = [String]() filter1Date[Wed, 06 May 2015 03:44:19 GMT, Wed, 06 May 2015 03:36:27 GMT, Wed, 06 May 2015 02:56:51 GMT, Wed, 06 May 2015...

display last 5days date in ios

ios,objective-c,nsdate
I am trying to display last 5 days date. But it display only last date(yesterday). I am using the following code to display it. .h file: NSInteger getDist; NSString *lastdate; NSDateFormatter *dateFormatter; NSDate *sevenDaysAgo; NSDate *dateAfterDecrement; NSString *dateString; int i; viewDidLoad: NSDate *currDate = [NSDate date]; dateFormatter = [[NSDateFormatter alloc]init];...

Using a variable property value for NSCalendarIdentifier return nil

ios,nsdate,nscalendar
I'm trying to init an NSCalendar with a value that is variable like below: NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:jam.calenderType]; But calendar always returns nil I know that: NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierIslamic]; And: NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; both work fine but I want the value to...

Default NSTimeInterval used by CoreData

ios,core-data,nsdate,nstimeinterval
NSDate value is returned by CloudKit. Which representation will system choose, when I am storing date in Core Data as NSTimeInterval? I know NSTimeInterval stores number of seconds since some specific reference date. But which reference date will be choosen here? mo.setValue(record.creationDate, forKey: "creationDate") Latter on I have to compare...

NSDateFormatter for day and month name

ios,objective-c,nsdate,nsdateformatter
I am trying to get date in the format Monday, March 09, 2015. But following code is not returning required date format. I think I am using wrong Formatter. Here is the code: NSString *dateString = @"09-03-2015"; NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd MMMM yyyy"]; NSDate *date =...

NSDate timeIntervalSince1970 not working in Swift?

swift,nsdate
I am doing this in swift: let date = NSDate(timeIntervalSince1970: 1432233446145.0) println("date is \(date)") The log gives me this: date is 47355-09-02 23:55:45 +0000 Then I try to get an interval back out just for testing: let tI = expirationDate.timeIntervalSinceDate(date) println("tI = \(tI)") I get: tI = 0.0 What am...

need to get central time in objective-c

ios,objective-c,nsdate,nstimezone
I have app where i need to get the current time (CST). I'm trying to use the following code but the NDate is the same as GMT: NSDate* date = [NSDate date]; NSLog(@"Time is %@", [date description]); [NSTimeZone setDefaultTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]]; NSDate* nDate = [NSDate date]; NSLog(@"Central time is%@", [nDate description])...

How to get the latest date from array in Swift

ios,swift,nsdate
I have an array of dates. I need to find the latest one. Can someone show me an example?

dateFromComponents returning wrong value

ios,objective-c,nsdate,nsdatecomponents
I'm trying to set the month and year of [NSDate date] but the function dateFromComponents return the wrong value, this is my code: NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian]; // Setup an NSCalendar NSDateComponents *components = [gregorianCalendar components: NSUIntegerMax fromDate: [NSDate date]]; // Setup NSDateComponents [components setTimeZone:[NSTimeZone defaultTimeZone]]; [components...

Swift - Convert Milliseconds into Minutes, Seconds and Milliseconds

swift,time,nsdate
I am writing a racing app and want to convert a large number of milliseconds into minutes:seconds.milliseconds (for example, 1:32.361). At the moment I just do it through maths (minutes / 60000), then get remainder and divide further, etc., but i find that it is off every now and then...

Issues in converting date string (any time zone) to NSDate of French Time Zone

ios,objective-c,nsdate,nsdateformatter,nstimezone
I want to convert a date string (can be in any time zone) to a date in French Time Zone. I am using following code. NSString * dateString = @"27/05/2015 - 19:00" // system time zone is GMT +5 NSDateFormatter* frenchDateFormatter = [[NSDateFormatter alloc] init]; [frenchDateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"Europe/Paris"]]; [frenchDateFormatter setDateFormat:@"dd/MM/yyyy...

CHANGE FORMAT TIME IN OBJECTIVE-C

ios,objective-c,nsdate,nsdateformatter
I need to change the format of my time and my date I search in Google how do that and I find how I can change the data format with that code: NSString *hora=@"01:32"; NSDateFormatter *formatHora = [[NSDateFormatter alloc] init]; [formatHora setDateFormat:@"hh:mm"]; NSDate *dateHora = [formatHora dateFromString:hora]; [formatHora setDateFormat:@"HH:mm"]; NSString*...

how to extract date components from sum of year month day weekday multiply by certain integer in iOS?

ios,nsdate,nsdatecomponents
The apple sample project DateSectionTitles demonstrates how to group sections by year and month, how to extends it to support year month day and weekday? sectionIdentifier is a transient attribute derives from persistent date attribute timestamp. - (NSString *)sectionIdentifier { // Create and cache the section identifier on demand. [self...

NSDateFormatter dateFromString return wrong year

ios,nsdate,nsdateformatter
I have these following snippet. NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat : @"yyyy/MM/dd"]; NSString *timeStr = @"2015/05/16"; NSDate *timeDate = [formatter dateFromString:timeStr]; But when I print timeDate in console,the output is werid.The year becomes 4003. 4003-05-16 16:00:00 +0000 I test it in iPad 8.3(12F69)(not simulator).System time zone is...

Sort an array by NSDates using the sort function [duplicate]

ios,arrays,swift,sorting,nsdate
This question already has an answer here: How do I sort a swift array containing instances of NSManagedObject subclass by an attribute value (date) 1 answer I have a model class called Event. import Foundation import MapKit public class Event { let id: Int var title: String? let status:...

NSDateFormatter adds 10hours?

ios,nsdate,nsdateformatter
I'm trying to get two dates from strings, so code below: NSString *serverDateString = array[0]; NSString *nextEventDateString = array[1]; NSDateFormatter *dateFormatter = [NSDateFormatter new]; [dateFormatter setDateFormat:@"hh:mm dd.MM.yyyy"]; timer.serverTime = [dateFormatter dateFromString:serverDateString]; timer.nextEventTime = [dateFormatter dateFromString:nextEventDateString]; But what i get : (lldb) po serverDateString 12:15 16.03.2015 (lldb) po nextEventDateString 00:00 17.03.2015...

How compare the user actual time with a NSArray?

objective-c,nsarray,nsdate,nstimer,nstimeinterval
I have a NSArray with many different hours as NSStrings. My question is, how can I compare the actual time of the user with the values into the NSArray and get which is the next hour to the actual user? For example, if the NSArray has got @"07:00", @"07:30", @"08:00",...

Convert date in long format to NSDate in iOS?

ios,objective-c,timestamp,nsdate
Iam getting date as "1425551087194" its in long format .How can i convert that into NSDate and display normal "mm-dd-yyyy" format. I have tried following codes and output also added here method 1: NSString * timeStampString =@"1425551087194"; NSTimeInterval _interval=[timeStampString longLongValue]; NSDate *date = [NSDate dateWithTimeIntervalSinceNow:_interval]; NSDateFormatter *_formatter=[[NSDateFormatter alloc]init]; [_formatter setDateFormat:@"dd.MM.yyyy"];...

parsing the date and getting the day off by 1, nsdate

ios,objective-c,nsdate,nsdateformatter,nsdatecomponents
There are two ending days like beloew A = 2029-12-31T00:00:00+00:00 B = 2029-12-31T12:00:00+00:00 I am getting the month, day and year by following NSDateFormatter *endDateFormatter = [[NSDateFormatter alloc] init]; [endDateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"]; NSDate *endDate = [endDateFormatter dateFromString:self[@"license"][@"endDate"]]; NSDateComponents *endDatecomponents = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:endDate]; This is what...

How to convert NSString to NSDate in IOS?

ios,objective-c,nsstring,nsdate,nsdateformatter
I am building an application where I need to convert The NSString to NSDate. I have googled and found a lot links of SOF mentioned below - http://stackoverflow.com/questions/3917250/converting-nsstring-to-nsdate-and- back-again Convert NSString to NSDate Converting can NSString to NSDate format in objective C I had used the answer given there but...

Create NSDate with String time from 1970

ios,objective-c,nsdate,nsdateformatter
I have a string that its value is time. The time is formmated with "time from 1970". How can I convert this string to a nsdate object?

Constructing NSDate using DateComponent gives inconsistent results

swift,nsdate,nsdatecomponents
I've created an extension for NSDate which removes the time component to allow equality checks for NSDate based on date alone. I have achieved this by taking the original NSDate object, obtaining the day, month and year using the DateComponent class and then constructing a new NSDate using the information...

Parsing a date string gives [__NSDate length] unrecognized selector exception [duplicate]

objective-c,cocoa,cocoa-touch,nsdate,nsdateformatter
This question already has an answer here: Converting NSDate to NSString causes unrecognized selector exception 2 answers I have an NSDictionary that holds a date like this: "2015-05-23 21:04:11 +0000" and I'm trying to parse it like: NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss z"]; NSDate *date...

Converting String into NSDate in array of dictionaries

arrays,swift,casting,nsdate,nsdictionary
I am doing some requests with an API that returns me the following sample : [{ id = 1004; "planning_id" = 7; "started_on" = "2015-05-14";}, { id = 1380; "planning_id" = 8; "started_on" = "2015-05-16";}, { id = 1382; "planning_id" = 8; "started_on" = "2015-05-18"; }] As you can see,...

Change NSDate to Friday of that Week

objective-c,nsdate,nsdatecomponents,nsdatecomponent
Currently I have the below code to increment my days to the next friday, however what I need is to get the friday of the current week. For example if it is last Sunday, 03/01. I would expect my response to be last Friday(02/28) not Friday(03/06). I have checked other...

Strange Behaviour of NSTimer

ios,xcode6,nsdate,nstimer,uidatepicker
Firstly, this is what I wan't to achieve: I want to run a timer from Current date and Time to user Selected Date and Time. What I have done: Made IBOutlet of DatePicker Made one UIButton What I have tried: - (IBAction)schedulePostTapped:(id)sender { [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateCountdown:) userInfo:nil repeats:YES];...

How to convert a string Date to NSDate in iOS

ios,nsdate
I googled so many times, but I am not satisfied with given answer. Please anyone can give correct answer what I need. This is the retrieve date string from DB : 2015-05-27 10:19 (yyyy-MM-dd HH:mm) I want to convert into NSDate. My code is like Below: NSString *date_str = @"2015-05-27...

What's the most efficient way to store time zone info in Realm?

ios,osx,nsdate,realm,foundation
I have a Realm object that contains an NSDate timestamp, representing the time at which a user recorded something. I need to add time zone info to this, so that I know what the local time zone was when the user created the object (in order to do accurate date...

Getting timezone offset from a date string

objective-c,nsdate,nsdateformatter
I have the following date as a string: 2015-04-18T08:35:00.000+03:00 and I would like to get an offset from the GMT in seconds, i.e. 10800. I can split the date string by '+' character, have a string xy:ab and then calculate the offset with formula xy*3600 + a*60 + b. Is...

NSDate Organization

ios,objective-c,iphone,twitter,nsdate
I am attempting to display timestamps in the S, M, H format however I get negative numbers on some accounts of the Minutes format. Better shown than said: The tweet by Chris is supposed to be 4m and the tweet by Mina is supposed to be 6m. Here is my...

Convert long month name to int

swift,cocoa-touch,nsdate,nsdateformatter,date-parsing
I understand how to use an NSDateFormatter to convert a month component into a long name string, but how does one convert a month name to an int? I've been using a switch statement to convert, but I'm thinking there must be a simpler way. For example, I'd like to...

Convert some date string into NSDate [closed]

ios,xcode,nsdate
From server I am receiving date string like - Date(1432224879000) Can someone please help me to convert above string into NSDate....

Format NSDate with different calendar identifier?

swift,nsdate,nsdateformatter,nsdatecomponents
I'm trying to print a human-friendly date that's of a different calendar identifier. I am able to get the date, but when I format it, it outputs back to Gregorian (or the user's current calendar I think). Here's what I'm trying: var calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierIslamicCivil) var flags = NSCalendarUnit(UInt.max)...

NSDate date to an unchangeable value [duplicate]

ios,objective-c,nsdate
This question already has an answer here: NSDate: Get precise time independent of device clock? [duplicate] 4 answers In my iOS app, I am using [NSDate date] to get the users' current datetime. This is an important element of the app but it seems that the users can change...

DateFormatter for format 'Fri, 19 Jun 2015 20:05:23 GMT'

ios,objective-c,nsdate,nsdateformatter
I am trying to determine the DateFormatter dateFormat element for the following timestamp: Fri, 19 Jun 2015 20:05:23 GMT I have tried the following without success: E', dd MMM yyyy hh:mm:ss zzz EE', dd MMM yyyy hh:mm:ss zzz EEE', dd MMM yyyy hh:mm:ss zzz E', dd MMM yyyy hh:mm:ss zz...

Rails API vs NSDate - Precision issues when comparing dates

ios,ruby-on-rails,ruby,datetime,nsdate
My iOS app consumes from a rails API that outputs JSON formatted dates with 3-digit microsecond precision, as per example below. This is parsed and saved for the corresponding entity, and NSDate retains the 3 digit precision as expected: { "updated_at": "2015-02-24T22:37:57.683Z" } When I send this date back to...

How in iOS to get first date of the month? [duplicate]

ios,objective-c,nsdate
This question already has an answer here: NSDateFormatter - 1 day incorrect? 1 answer I try to get first date for the current month from [NSDate new]. My problem is that instead of 2015/06/01 I always receive 2015/05/31. I even try to convert string 20150601 to NSDate and I...

Check if the given date time is between two others date time in Objective C

ios,objective-c,datetime,nsdate
I am trying to figure out the way to check my date time is between two others date time, for example I am getting current time from my server as "Mar 16 2015 14:17" so I want to check that whether this date time is between two others date time...

String to NSdate not working

ios,nsdate,nsdateformatter
I want to convert the string 3/12/15 to NSdate. And i am using the below code. But after converting, the date becomes 2015-03-11 18:00:00 +0000. But i want the same format just like it is now in string. Any kind of help would be very appreciative. NSDateFormatter *df = [[NSDateFormatter...

NSDate - dateFromString is returning nil

ios,objective-c,nsdate
I have an NSString that has a date. I'm trying to convert that date to an NSDate. When I do that I get nil fro the NSDate. Here is my code: NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"dd/MM/yyyy"]; NSDate *date = [dateFormatter dateFromString:dateString]; NSLog(@"dateString = %@ date = %@",...

NSDateFormatter- stringFromDate not returning AM/PM

ios,datetime,nsdate,nsdateformatter,date-format
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"hh:mm:ss a"]; NSLog(@"Today's Time: %@", [formatter stringFromDate:[NSDate date]]); The above code just gives the following output Today's Time: 15:46:43 I want the output to be Today's Time: 3:46 PM. I surfed a lot and i did not find a way to show...

NSDate has the opposite AM/PM value

ios,swift,nsdate
I am using this code to convert the NSDate to my local timezone, the correct hour and day is shown but the AM/PM part is always incorrect. let date1 = "2015-05-14 19:00:00 +0000" let date2 = "2015-06-12 04:50:00 +0000" var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss zzzz" let date...

Find the time/date from min./hours/seconds swift 1.2 xcode 6.3

swift,nsdate,nscalendar
Sorry My Title Is So Bad. :( I am making a app to find out how long it will be before you have to go collect your belongings from a game. So you enter how much ore you want and it will do the math, It will tell you how...

Change date in UILabel when click next and previous UIButton

ios,objective-c,uilabel,nsdate,updates
Set a date in UILabel. The click on "next" and "previous" buttons should change date inside this label. I'm trying this code but next button click and show date next day date for e.g 01/05/2015 and previous button click and set date 29/05/2015 and next button click not display 02/05/2015...

Using dateFromString api of date formatter in a for loop giving huge memory issues

ios,objective-c,nsdate,nsdateformatter
I created an instance of NSDateFormatter outside the for loop( or can say an instance variable) and then used it in a for loop as [dateFormatter dateFromString]. This is giving me huge memory issues. I tried lowering the huge memory allocations using the @autorelease directive where I have moved the...

creating a wrong NSDate

ios,objective-c,iphone,cocoa,nsdate
This is the code NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:13]; [comps setMonth:6]; [comps setYear:2015]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDate *date = [gregorian dateFromComponents:comps]; NSLog(@"date = %@", date); the result is 2015-06-12 23:00:00 +0000 12? the day is 13!!! Why is that happening? Bug? ...

objective c - NSDateFormatter incorrect output [duplicate]

objective-c,xcode,nsdate,nsdateformatter
This question already has an answer here: returns a date an hour in the future 1 answer Why does the below code output the incorrect Date after conversion? NSString *customDate = @"23-06-1993"; NSLog(@"Custom Date: %@", customDate); NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"dd-MM-yyyy"]; NSDate *birthDayDate = [formatter dateFromString:customDate];...

How to get start date of current year in iOS

ios,objective-c,nsdate,nscalendar
I don't know how to use NSDate or NSCalendar in this condition. Help me to solve this issue.

Difference between two NSDate expansion

ios,nsdate,nstimeinterval
i know how to get difference between two NSDate as follow NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:anyPreviousDate]; and i know it will return me NSTimeInterval in positive seconds. what I want to know is what it will return if my anyPreviousDate is greater than [NSDate date] i.e. anyPreviousDate has not...

Xcode Swift NSDate Custom [duplicate]

xcode,swift,date,nsdate
This question already has an answer here: Leading zeros for Int in Swift 2 answers I want a date as 07:05 or 16:25 I tried but it does not work exactly var array1 = ["05:30","05:50","06:10","06:30","06:50","07:05","07:13","07:19","07:25","07:30","07:35","07:40","07:46","07:53","07:59","08:06","08:12","08:20","08:28","08:37","08:46","08:55","09:05","09:15","09:25","09:35","09:45","09:55","10:05","10:15","10:25","10:35","10:45","10:55","11:05","11:15","11:25","11:35","11:45","11:55","12:05"] var arrr = [String()] let dateFormatter =...

Create own NSDate

swift,xcode6,nsdate,nscalendar
I would like to create an NSDate. It should be the year 1, the month 1, the day 1, the minute 0, the seccond 0 and the nanoseccond 0. I don not know how I can create this day myself. So do you guys know how to do this in...

How to compose date from first NSDate and time from second NSDate into one NSDate?

ios,swift,nsdate
I need one thing: create one output NSDate that includes both of them with format: "yyyy-MM-dd HH:mm:00", where yyyy-MM-dd is from first NSDate and HH:mm:00 is from second NSDate ...

Swift: NSDate losing sub-Second precision after loading

ios,swift,xcode6,nsdate
I have a 2-dimensional array of NSDates, working at sub-second precision. But when I save the array like this: let pathes = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray let documentsDirectory = pathes.objectAtIndex(0) as! NSString let path = documentsDirectory.stringByAppendingPathComponent("tj_001.plist") var dicti = NSMutableDictionary() dicti.setObject(tDate, forKey: "tTimes") dicti.writeToFile(path, atomically: false) and load it...

iOs - error with NSDateFormatter

ios,nsdate,date-format
I have a Date with value 2015-05-31 22:00:00 UTC (I parse it from a NSString with value "01-06-2015" and it give that value) and when I parse it it become 01-06 why?? I need to get on nextdate the value = 2015-06-1 22:00:00 UTC because I need to get the...

Get current NSDate with a format of: dd/MM/yyyy

objective-c,nsdate,nsdateformatter
I'm trying to get the current date with the following format: dd/MM/yyyy. The way I would format it, is like this: NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"dd/MM/yyyy"]; And I would get the current date like this: [NSDate date]. How can I mix the 2 together, and get the...

iOS convert date to string AM/PM

ios,objective-c,nsdate
-(NSString *)calculateDateToString:(NSDate *)getDate { NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss"]; [dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; NSString *dateString = [dateFormat stringFromDate:getDate]; return dateString; } This method work when time format 24H but if time came with AM/PM this method not work. I set date format but still not work which part...

Get NSDate from start of 7 days ago

ios,objective-c,nsdate
I'm trying to do some simple 7 day history plotting. Given the current NSDate.date, I want to get the NSDate that corresponds to the start of day, 7 days ago. So basically 7 days prior to 0.00 this morning. What I've tried, is the following: // decompose the current date,...

Parse NSDate with format @“MMM dd ''YY”

ios,objective-c,string,parsing,nsdate
I have a date string which looks like this: Mar 13 '15 I am not able to find the right way to parse this. I've tried the following: NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"MMM dd ''YY"]; //[df setDateFormat:@"MMM dd 'YY"]; //[df setDateFormat:@"MMM dd YY"]; NSDate *date = [df...

Weekday Local Notification Not Firing

ios,ios8,nsdate,uilocalnotification,repeat
I'm building an application that allows the user to have a local notification to repeat every weekday, because apple doesn't have a repeat interval for WeekDays I needed to create a local notification for every week day. I made a for loop looping 5 times the number of days in...

How to execute function based on day?

ios,swift,nsdate
I have a function that is shown below that executes a function based on the hour. How can I modify it to also execute based on the day of WEEK? let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitHour, fromDate: date) let hour = components.hour if(hour >=...

timeIntervalSinceDate reporting wrong value

ios,objective-c,nsdate,nstimeinterval
I've got two dates that are set with a button press. These are stored in a custom object that inherits from NSObject. Properties: @property (nonatomic, strong) NSDate *firstDate; @property (nonatomic, strong) NSDate *secondDate; Custom getter and setter methods: - (void)setFirstDate:(float)firstDate { _firstDate = [self dateByOmittingSeconds:firstDate]; } - (void)setSecondDate:(float)secondDate { _secondDate...

Convert epoch milliseconds to NSDate

ios,objective-c,timestamp,nsdate,epoch
I want to convert milliseconds elapsed since Jan 1 1970 to NSDate without loosing milliseconds. Every solution says to divide milliseconds by 1000 and use dateWithTimeIntervalSince1970. but I want to keep the preserve the to milliseconds as well.

Compare the month and day of two NSDates

ios,objective-c,nsdate
I need to setup an if/else statement that compares only the month and day of two NSDates. One of the dates is selected with a UIDatePicker and the other would be today's date. If the month and date of the two are the same, something happens, if not something else...

How to turn NSString hexInterval into NSTimeInterval for date conversion

ios,objective-c,nsdate,nstimeinterval
Currently, I am working with an existing array of NSDates in the following format: NSDate *today = [NSDate date]; //today is used as an example NSTimeInterval interval = [today timeIntervalSince1970]; NSString *hexInterval = [NSString stringWithFormat:@"%08x", (int)interval]; NSLog(@"hexInterval %@", hexInterval); The dates are outputted in a format such as 4ec2acf0. My...

NSDate is older than today

ios,objective-c,nsdate
I understand how to compare two NSDate objects, e.g: if ([olderDate compare:[NSDate date]] == NSOrderedAscending) { // do something } However I would like to just compare date components, not time since time can make the comparison inaccurate in my case. Is it possible to just compare day, month and...

NSSortDescriptor NSDate ascending. How to sort objects with the same date?

ios,swift,nsdate,nssortdescriptor
I am using an NSFetchedResultsController to display objects Event in a list. The Event-object has a property of startDate and an eventType property which is an enum of types CheckIn, Concert, Meeting, Flight, CheckOut. The NSFetchedResultsController has a sortDescriptor that orders the events by its startDate: eventsRequest.sortDescriptors = [NSSortDescriptor(key: "startDate",...

Why compareDate from NSCalendar seems to need to set an UTC timeZone to work properly?

ios,timezone,nsdate,nscalendar
I create two dates like the following: let date1 = stringToDate("2015-02-12 12:29:29")! let date2 = stringToDate("2015-02-11 19:18:49")! func stringToDate(var dateString: String) -> NSDate? { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" dateFormatter.timeZone = NSTimeZone(name: "UTC") return dateFormatter.dateFromString(dateString) } As you can see, the two date are different and are...

How to subtract time from NSDate with the help of NSDateFormatter?

ios,objective-c,nsdate,nsdateformatter
I'm working on an application in which user set a time to do a task and before 10 or 15 minutes application triggers an alarm. Just like a reminder app you can say. After searching a lot on stackOverFlow and other different links my problem still exists. Here is what...

NSCalendar set firstWeekDay to monday but results are different

ios,iphone,nsdate,nscalendar
I am trying to get the beginning date of a month. - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"begining of month: %@ from today", [self beginningOfMonth:[NSDate date]]); } - (NSDate *)beginningOfMonth:(NSDate *)date { NSCalendar *calendar = [NSCalendar currentCalendar]; calendar.locale = [NSLocale currentLocale]; calendar.timeZone = [NSTimeZone defaultTimeZone]; calendar.firstWeekday = 2; NSDateComponents *componentsCurrentDate =...

NSDate day of the year (swift)

ios,swift,nsdate
How might the day number of the year be found with swift? Is there a simple way that I'm not seeing, or do I have to find the number of seconds from Jan 1 to the current date and divide by the number of seconds in a day?

Swift - convert date string from a “datepicker filled date field” to nsdate

swift,nsdate,nsdateformatter,uidatepicker
Ive got a UIDatepicker attached to a text field named dateField. when the user clicks on the field, a UIDatePicker pops up and the user chooses a date of birth. That date is saved as a string to that dateField and shows up formatted according to the users location ie...

Get the object with the most recent date

ios,swift,nsdate
I have an array of objects of type Thing: class Thing: NSObject { var data: String var type: String var created: NSDate } These things have an NSDate property called created. My aim is to write a function that reads the created property of every thing in the array and...

NSArray with week days

ios,objective-c,nsdate,nsdateformatter
I have a question, In my app I have an NSMutableArray which contains name with days of the week, sometimes is just Sunday and Saturday, sometimes is just Monday or Tuesday, my question is: I want that when my array will contain just entry like this: Sunday and Saturday to...

How can I get an NSDate representation of a specific hour in the day of another NSDate?

ios,swift,nsdate
I need to get an NSDate for a specific hour of the day based on another NSDate. For example, if I have an NSDate representing a known time on May 10th, 2015, I need to be able to get an NSDate representing 01:00 on May 10th, 2015. How would I...

NSDateComponentsFormatter's stringFromDate(_, toDate:) returns nil

swift,nsdate,nsdateformatter,nsdatecomponents,nsdatecomponentsformatter
Question Why is string nil? let formatter = NSDateComponentsFormatter() let referenceDate = NSDate(timeIntervalSinceReferenceDate: 0) let intervalDate = NSDate(timeInterval: 3628810, sinceDate: referenceDate) let string = formatter.stringFromDate(referenceDate, toDate: intervalDate) I'm expecting a string like "6w 10s" to be returned. (6 weeks is 3,628,800 seconds.) Attempted Troubleshooting To troubleshoot, I tried setting allowedUnits:...

How to parse the timezone in this date string?

ios,nsdate
I would like to convert this string to NSDate: "Sun, 08 Mar 2015 10:32:12 -0000" This is what I got working: NSDateFormatter *dateformatter = [NSDateFormatter new]; [dateformatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss"]; NSDate *date = [dateformatter dateFromString:@"Sun, 08 Mar 2015 10:32:12"]; But I don't know how to parse the -0000,...

time change after converting using NSDateFormatter

objective-c,nsdate,nsdateformatter
I'm trying to convert string to date. it works fine but the hours is different from the string. Here is my sample code: NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss a"]; [dateFormat setTimeZone:[NSTimeZone defaultTimeZone]]; [dateFormat setLocale:[NSLocale currentLocale]]; NSDate *date = [dateFormat dateFromString:@"2015-03-09 07:40:00 pm"]; NSLog(@"%@", date); And, the...

Converting different strings to NSDate - 1 is correct, the 2nd is a duplicate of the 1st

objective-c,nsdate,nsdateformatter,ios8.1
For some reason, this code is not converting the second string correctly; this is the code: NSLog(@"\n\nsearchStartTime: %@ searchEndTime: %@",searchStartTime, searchEndTime); [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm a"]; startDate = [dateFormatter dateFromString:searchStartTime]; endDate = [dateFormatter dateFromString:searchEndTime]; NSLog(@"\n\nstartDate: %@ endDate: %@", startDate, endDate); This the definition and value of the searchStartTime and searchEndTime:...