How to convert timestamp to nsdate - objective-c

I have a timestamp as below. Its in a string format
"/Date(1402987019190+0000)/"
I would like to convert it into NSDate. Can somebody help me into this one?

Use dateWithTimeIntervalSince1970:,
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeStamp];
NSLog(#"%#", date);
Use this function to convert string to timestamp Ref. https://stackoverflow.com/a/932130/1868660
-(NSString *)dateDiff:(NSString *)origDate {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:#"EEE, dd MMM yy HH:mm:ss VVVV"];
NSDate *convertedDate = [df dateFromString:origDate];
[df release];
NSDate *todayDate = [NSDate date];
double ti = [convertedDate timeIntervalSinceDate:todayDate];
ti = ti * -1;
if(ti < 1) {
return #"never";
} else if (ti < 60) {
return #"less than a minute ago";
} else if (ti < 3600) {
int diff = round(ti / 60);
return [NSString stringWithFormat:#"%d minutes ago", diff];
} else if (ti < 86400) {
int diff = round(ti / 60 / 60);
return[NSString stringWithFormat:#"%d hours ago", diff];
} else if (ti < 2629743) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:#"%d days ago", diff];
} else {
return #"never";
}
}

If I correctly understood what you mean, you need to parse timestamp from the string with given format.
You can use regular expression to extract timestamp value.
NSString * timestampString = #"/Date(1402987019190+0000)/";
NSString *pattern = #"/Date\\(([0-9]{1,})\\+0000\\)/";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:timestampString options:0 range:NSMakeRange(0, timestampString.length)];
NSRange matchRange = [textCheckingResult rangeAtIndex:1];
NSString *match = [timestampString substringWithRange:matchRange];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[match intValue];
NSLog(#"%#", date);

Related

Objective-C Xcode - if statement "Expected expression"

i must check if the interval between 2 times is > 0 then set the text of a label but i get "Expected expression" when i use the if statement..
NSDate * now = [NSDate date];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:#"HH:mm:ss"];
NSString *newDateString = [outputFormatter stringFromDate:now];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm:ss"];
NSDate *date1 = [df dateFromString:newDateString];
NSDate *date2 = [df dateFromString:#"15:00:00"];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
int seconds = interval - ((hours*3600)+(minutes*60)) ;
NSString *timeDiff = [NSString stringWithFormat:#"%02d | %02d | %02d", hours, minutes, seconds];
if (interval < 0)
{
self.before3.text = timeDiff;
}
The error is on if (interval < 0)
Can someone help me please?
Regards.

Manipulate string in objective-c to remove substring between 2 characters

I want to parse a date string that I receive from a web service. However, I sometimes receive the date with decimal component and sometimes without decimal component. Also, sometimes the date comes with a different number of decimal digits.
Assume you got the following date:
NSString *dateString = #"2013-07-22T220713.9911317-0400";
How can remove the decimal values? I want to end up with:
#"2013-07-22T220713-0400";
So I can process it with the DateFormatter that uses no decimal.
You could use a regular expression to match the first occurrence of a decimal followed by numbers, and remove them:
NSString *dateString = #"2013-07-22T220713.9911317-0400";
NSRegularExpression * regExp = [NSRegularExpression regularExpressionWithPattern:#"\\.[0-9]*" options:kNilOptions error:nil];
dateString = [dateString stringByReplacingCharactersInRange:[regExp rangeOfFirstMatchInString:dateString options:kNilOptions range:(NSRange){0, dateString.length}] withString:#""];
Based on #JeffCompton 's suggestion I ended up doing this:
+ (NSDate *)dateFromISO8601:(NSString *)dateString {
if (!dateString) return nil;
if ([dateString hasSuffix:#"Z"]) {
dateString = [[dateString substringToIndex:(dateString.length - 1)] stringByAppendingString:#"-0000"];
}
NSString *cleanDateString = dateString;
NSArray *dateComponents = [dateString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"."]];
if ([dateComponents count] > 1){
NSArray *timezoneComponents = [[dateComponents objectAtIndex:1] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"-"]];
if ([timezoneComponents count] > 1){
cleanDateString = [NSString stringWithFormat:#"%#-%#", [dateComponents objectAtIndex:0], [timezoneComponents objectAtIndex:1]];
}
}
dateString = [cleanDateString stringByReplacingOccurrencesOfString:#":" withString:#""];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-d'T'HHmmssZZZ";
NSDate *resultDate = [dateFormatter dateFromString:dateString];
return resultDate;
}
This is a modification of some open-source code but I lost the reference to the original code.
The reason for all the modifications is that I am connecting to API's that can give me the date with decimals or without, and sometimes without the : separating HH, mm, and ss.

NSTimeInterval Formatting

I want to take my NSTimeInterval and format it into a string as 00:00:00 (hours, minutes, seconds). What is the best way to do this?
Since iOS 8.0 there is now NSDateComponentsFormatter which has a stringFromTimeInterval: method.
[[NSDateComponentsFormatter new] stringFromTimeInterval:timeInterval];
"Best" is subjective. The simplest way is this:
unsigned int seconds = (unsigned int)round(myTimeInterval);
NSString *string = [NSString stringWithFormat:#"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
UPDATE
As of iOS 8.0 and Mac OS X 10.10 (Yosemite), you can use NSDateComponentsFormatter if you need a locale-compliant solution. Example:
NSTimeInterval interval = 1234.56;
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute |
NSCalendarUnitSecond;
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
NSString *string = [formatter stringFromTimeInterval:interval];
NSLog(#"%#", string);
// output: 0:20:34
However, I don't see a way to force it to output two digits for the hour, so if that's important to you, you'll need to use a different solution.
NSTimeInterval interval = ...;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(#"hh:mm:ss %#", formattedDate);
swift 4.2
extension Date {
static func timestampString(timeInterval: TimeInterval) -> String? {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.zeroFormattingBehavior = .pad
formatter.maximumUnitCount = 0
formatter.allowedUnits = [.hour, .minute, .second]
return formatter.string(from: timeInterval)
}
}
Test code:
let hour = 60 * 50 * 32
Date.timestampString(timeInterval: TimeInterval(hour))
// output "26:40:00"
Change unitStyle to get different styles. like formatter.unitsStyle = .abbreviated get
output: "26h 40m 0s"
A Swift version of #Michael Frederick's answer :
let duration: NSTimeInterval = ...
let durationDate = NSDate(timeIntervalSince1970: duration)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let durationString = dateFormatter.stringFromDate(durationDate)

Localized date (month and day) and time with NSDate

I want to be able to get the local date and time for wherever my app is run, based on the iPhone configuration. Specifically I need the date to be of format mm/dd or dd/mm (or dd.mm, mm.dd, dd-mm, mm-dd, etc) depending on the locale, and time is hh:mm. Is this possible with some combination of SDK methods?
Thanks!
I have modified the code so that it just takes the date and time out of the NSDate object with no changes:
NSDate* date = [NSDate date];
NSString* datePart = [NSDateFormatter localizedStringFromDate: date
dateStyle: NSDateFormatterShortStyle
timeStyle: NSDateFormatterNoStyle];
NSString* timePart = [NSDateFormatter localizedStringFromDate: date
dateStyle: NSDateFormatterNoStyle
timeStyle: NSDateFormatterShortStyle];
NSLog(#"Month Day: %#", datePart);
NSLog(#"Hours Min: %#", timePart);
Well, I believe the following code works for what I need:
NSString *dateComponents = #"yMMd";
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:[NSLocale currentLocale]];
NSArray *tmpSubstrings = [dateFormat componentsSeparatedByString:#"y"];
NSString *tmpStr;
NSRange r;
if ([[tmpSubstrings objectAtIndex:0] length] == 0) {
r.location = 1;
r.length = [[tmpSubstrings objectAtIndex:1] length] - 1;
tmpStr = [[tmpSubstrings objectAtIndex:1] substringWithRange:r];
} else {
r.location = 0;
r.length = [[tmpSubstrings objectAtIndex:0] length] - 1;
tmpStr = [[tmpSubstrings objectAtIndex:0] substringWithRange:r];
}
NSString *newStr = [[NSString alloc] initWithFormat:#"%# H:mm", tmpStr];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:newStr];
NSString *formattedDateString = [formatter stringFromDate:[NSDate date]];

How to display date as "15th November 2010" in iPhone SDK?

HI,
I need to display date as "15th November 2010" in iPhone SDK.
How do I do that?
Thanks!
You can use a Date Formatter as explained in this post:
// Given some NSDate* date
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"dd MMM yyyy"];
NSString* formattedDate = [formatter stringFromDate:date];
I believe you can simply just put "th" at the end of the dd in the format string. like this:
#"ddth MMM yyy
but I don't have my Mac in front of me to test it out. If that doesn't work you can try something like this:
[formatter setDateFormat:#"dd"];
NSString* day = [formatter stringFromDate:date];
[formatter setDateFormat:#"MMM yyyy"];
NSString* monthAndYear = [formatter stringFromDate:date];
NSString* date = [NSString stringWithFormat:#"%#th %#", day, monthAndYear];
I know I'm answering something old; but I did the following.
#implementation myClass
+ (NSString *) dayOfTheMonthToday
{
NSDateFormatter *DayFormatter=[[NSDateFormatter alloc] init];
[DayFormatter setDateFormat:#"dd"];
NSString *dayString = [DayFormatter stringFromDate:[NSDate date]];
//yes, I know I could combined these two lines - I just don't like all that nesting
NSString *dayStringwithsuffix = [myClass buildRankString:[NSNumber numberWithInt:[dayString integerValue]]];
NSLog (#"Today is the %# day of the month", dayStringwithsuffix);
}
+ (NSString *)buildRankString:(NSNumber *)rank
{
NSString *suffix = nil;
int rankInt = [rank intValue];
int ones = rankInt % 10;
int tens = floor(rankInt / 10);
tens = tens % 10;
if (tens == 1) {
suffix = #"th";
} else {
switch (ones) {
case 1 : suffix = #"st"; break;
case 2 : suffix = #"nd"; break;
case 3 : suffix = #"rd"; break;
default : suffix = #"th";
}
}
NSString *rankString = [NSString stringWithFormat:#"%#%#", rank, suffix];
return rankString;
}
#end
I grabbed the previous class method from this answer: NSNumberFormatter and 'th' 'st' 'nd' 'rd' (ordinal) number endings