Issue while parsing timestamp into date and time using Objective-C - objective-c

I am getting timestamp for server in stringFormat which is in miliseconds.
I have to convert it in date and time and display to the user.
I have done it using following code:
+ (NSString *)getDateAndMonthFromTimeStamp:(NSString*)timestampString
{
NSTimeInterval timeStamp = [timestampString integerValue]/1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
[dateFormatter setDateFormat:#"dd MMM"];
NSString *dateNmonth = [[dateFormatter stringFromDate:date]uppercaseString];
return dateNmonth;
}
When I run it in iPhone6 it works fine. But when I run it in iPhone 5 and iPhone5s it shows me unwanted date.
I debug the code and found this:
timestampString = #"1459498716000"
NSTimeInterval timeStamp = [timestampString integerValue]/1000;
//after this timeStamp becomes:
timeStamp = 2147483;
and then my date becomes 1970-01-25 20:31:23 +0000
I am in doubt that NSTimeinterval is overflowed with data. is this right?
How can I fix this.

try this code
NSString* takeOffTime = #"1396614600000";
double miliSec = takeOffTime.doubleValue;
NSDate* takeOffDate = [NSDate dateWithTimeIntervalSince1970:miliSec/1000];

Related

Converting timestamp into NSDate

I have a date in timestamp which looks something like this: 1474914600000
Now, I want to covert this timestamp to NSDate in format of dd-mm-yyyy.
How can this be done in objective c?
You need to convert your timestamp to NSDate and then get NSDate in your desired format. Also your timestamp seems to be in millisecond so you will have to divide it be 1000. You can use below code:
double timeStamp = 1474914600000;
NSTimeInterval timeInterval=timeStamp/1000;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setDateFormat:#"dd-MM-yyyy"];
NSString *dateString=[dateformatter stringFromDate:date];
dateString value as an output will be: "27-09-2016"
Hope it helps.
To elaborate on balkaran's answer incase you're new to the iOS world. The timestamp you provided seems to go down to milliseconds which you wouldn't need for day times that's why he's dividing by 1000. You would use the dateformatter as follows to return an NSString you can use with the formatted date.
NSDate *date = [NSDate dateWithTimeIntervalSince1970:1474914600000];
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = #"dd-MM-yyyy";
NSString *formattedDate = [formatter stringFromDate:date];
use this:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp/1000];
then convert your date in the format you want.

Problems formatting dates

Here is the set up, I have a JSON feed I am using and I want to find the difference between two specific dates called posted_date and planned_expiration_date. They are in an odd format I so I thought I could truncate them down to just the date.I could then use NSTimeInterval to find the difference in seconds.
// Time Interval Left
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSString *startDate = [firstPerson objectForKey:#"posted_date"];
NSString *endDate = [firstPerson objectForKey:#"planned_expiration_date"];
//Ammend the strings to YYYY-MM-DD
[formatter setDateFormat:#"yyyy-mm-dd"];
int newlength = 9;
NSDate *startDateAmmended =[formatter dateFromString:[startDate substringFromIndex:newlength]];
NSDate *endDateAmmended = [formatter dateFromString:[endDate substringFromIndex:newlength]];
Here is the bit I'm not too sure about. The date appears something like this "2013-06-07T13:40:01Z" straight from the feed. I don't know how to deal with the T and Z chars in the date formatter method so I truncate the string with substringFromIndex to make it 10 chars and then attempted the following code.
//Difference in Date
NSTimeInterval *startDifference = [startDateAmmended timeIntervalSinceNow];
NSTimeInterval *endDifference = [endDateAmmended timeIntervalSinceNow];
NSTimeInterval timeDifferenceInSeconds = startDifference - endDifference;
I get the following error, .../JSONParser/ViewController.m:52:21: Initializing 'NSTimeInterval *' (aka 'double *') with an expression of incompatible type 'NSTimeInterval' (aka 'double') at the first two calls to NSTimeInterval.
I am sure I'm going wrong in a few places and I'm sure this isn't the easiest method of doing it. Could anyone recommend how I would fix this issue or an easier way to go about getting the differences between dates?
Your error comes from your lines that say:
NSTimeInterval *startDifference = [startDateAmmended timeIntervalSinceNow];
NSTimeInterval *endDifference = [endDateAmmended timeIntervalSinceNow];
They should be:
NSTimeInterval startDifference = [startDateAmmended timeIntervalSinceNow];
NSTimeInterval endDifference = [endDateAmmended timeIntervalSinceNow];
Or, more simply, don't define those two difference variables at all, and just use:
NSTimeInterval timeDifferenceInSeconds = [endDateAmmended timeIntervalSinceDate:startDateAmmended];
To calculate the difference between two ISO 8601 / RFC 3339 date strings, you can do:
NSDate *startDate = [self dateFromISO8601String:#"2013-06-01T16:27:35Z"];
NSDate *endDate = [self dateFromISO8601String:#"2013-06-07T13:40:01Z"];
NSTimeInterval elapsed = [endDate timeIntervalSinceDate:startDate];
NSLog(#"Time elapsed (in seconds) is %.0f", elapsed);
where dateFromISO8601String is defined as:
- (NSDate *)dateFromISO8601String:(NSString *)string
{
static NSDateFormatter *formatter = nil;
if (formatter == nil)
{
formatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
formatter.locale = enUSPOSIXLocale;
formatter.dateFormat = #"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'";
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
}
return [formatter dateFromString:string];
}
You can get the difference in seconds between two NSDate objects like this:
double difference = [startDateAmmended timeIntervalSinceDate:endDateAmmended];
Note that with the substring operation you don't have the time, only the date, so the difference will be in seconds but with steps of whole days.

current Date and Time - NSDate

I need to display the current Date and Time.
I have used ;
NSDate *currentDateNTime = [NSDate date];
I want to have the current date and time (Should display the system time and not GMT time).
The output should be in a NSDate format and not NSString.
for example;
NSDate *currentDateNTime = [NSDate date];
// Do the processing....
NSDate *nowDateAndTime = .....; // Output should be a NSDate and not a NSString
Since all NSDate is GMT referred, you probably want this:
(don'f forget that the nowDate won't be the actual current system date-time, but it's "shifted", so if you will generate NSString using NSDateFormatter, you will see a wrong date)
NSDate* currentDate = [NSDate date];
NSTimeZone* currentTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* nowTimeZone = [NSTimeZone systemTimeZone];
NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:currentDate];
NSInteger nowGMTOffset = [nowTimeZone secondsFromGMTForDate:currentDate];
NSTimeInterval interval = nowGMTOffset - currentGMTOffset;
NSDate* nowDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:currentDate];
Every moment in time is the same moment in time everywhere around the world —- it is just expressed as different clock times in different timezones. Therefore, you can't change the date to some other date that represents the time in your timezone; you must use an NSDateFormatter that you feed with the timezone you are in. The resulting string is the moment in time expressed in the clock time of your position.
Do all needed calculations in GMT, and just use a formatter for displaying.
Worth reading
Does [NSDate date] return the local date and time?
Some useful resources for anyone coming to this more recently:
Apple date and time programming guide do read it if you're doing anything serious with dates and times.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html#//apple_ref/doc/uid/10000039i?language=objc
Useful category on NSDate with lots of utilities does allow a ~new~ date to be generated based on an existing date.
https://github.com/erica/NSDate-Extensions
There's also a swift version of the category
https://github.com/erica/SwiftDates
You need an NSDateFormatter and call stringFromDate this method to get a string of your date.
NSDateFormatter *dateformater = [[NSDateFormatter alloc] init];
[dateformater setDateFormat:#"yyyyMMdd,HH:mm"];
NSString *str = [dateformater stringFromDate: currentDateNTime];
use this method
-(NSDate *)convertDateToDate:(NSDate *) date
{
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
[formatter setDateFormat:#"yyyy-MM-d H:m:s"];
NSString * strdate = [formatter stringFromDate:date];
nowDate = [formatter dateFromString:strdate];
return nowDate;
}
this may return you what you want.
i hope you this may help you.

converting timestamp to nsdate format

I want to convert my timestamp value 1308031456 to NSDate format (which yields the value Tue, 14 Jun 2011 06:04:16 GMT in online web conversion). How would I convert between the two programmatically?
OBJ - C:
Use dateWithTimeIntervalSince1970:,
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
SWIFT:
Use init(timeIntervalSince1970:)
let date = NSDate(timeIntervalSince1970:timeStamp)
You can use the use the method dateWithTimeIntervalSince1970: to convert the timestamp you've which is the epoch time.
NSDate * myDate = [NSDate dateWithTimeIntervalSince1970:1308031456];
In obj c
double timeStamp = 1513330403393;
NSTimeInterval unixTimeStamp = timeStamp / 1000.0;
NSDate *exactDate = [NSDate dateWithTimeIntervalSince1970:unixTimeStamp];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"dd/MM/yyy hh:mm a";
NSString *finalate = [dateFormatter stringFromDate:exactDate];
In Swift
let timeStamp = 1513330403393
let unixTimeStamp: Double = Double(timeStamp) / 1000.0
let exactDate = NSDate.init(timeIntervalSince1970: unixTimeStamp)
let dateFormatt = DateFormatter();
dateFormatt.dateFormat = "dd/MM/yyy hh:mm a"
print(dateFormatt.string(from: exactDate as Date))
See the various example on date formatting and getting date from timestamp from apple
Use Formatter Styles to Present Dates and Times With the User’s Preferences
Convert TimeStamp to NSDate in Objective-C
Here is a code piece which lets you convert the unix type timestamp to Formatted Date
NSString * timeStampString =#"1304245000";
NSTimeInterval _interval=[timeStampString doubleValue];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
[_formatter setDateFormat:#"dd.MM.yyyy"];
NSString *_date=[_formatter stringFromDate:date];
This will print _date something like 05.03.2011

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);