How to get the NSDateFormatter like the one used to generate string on the right.
simply use the setDoesRelativeDateFormatting is not enough.
And using NSCal to figure out the date's relativity to now is quiet slow.
Especially when used in UITableViewCell
You can use a "fuzzy date" library such as NSDate-TimeAgo.
They are likely using 2 formatters...
maybe something like :
- (id)stringForDate:(NSDate*)date {
if(date isToday]) return time
else return date day
}
NSDateFormatter *f = [[NSDateFormatter alloc] init];
f.dateFormat = #"yyyy MM dd";
NSDate *today = [NSDate date];
NSDate *your_Date;
NSString *a = [f stringFromDate today];
NSString *b = [f stringFromDate your_Date];
if (a isEqualToString:b){
NSdateFormatter *forToday =... //with hours
} else {
NSDateFormatter *forDays = ...//days
}
Related
consider the string like "2017-08-30T06:40:00.000+00:00"
1 - How to convert this string into timestamp
2 - How to group this value into time slots (for eg, if the value is time = 2:30 PM, it will be grouped into the slot of 2pm to 3pm)
I will help you with an idea in objective C try converting to the swift, If not you can ask me. I will help you out with the right code. Write a function like this generically and use it in the places wherever you wanted to convert the date format.
+ (NSString*)dateFormatConv:(NSString *)givenFormat DateValue:(NSString*)dateString needFormat:(NSString *)reqFormat LabelName:(UILabel *)lbl{
NSString *myDateString = dateString;
NSDateFormatter *DateFormatter=[[NSDateFormatter alloc] init];
[DateFormatter setDateFormat:givenFormat];
NSDate *date = [DateFormatter dateFromString:myDateString];
[DateFormatter setDateFormat:reqFormat];
NSString *dateString2 = [DateFormatter stringFromDate:date];
lbl.text = dateString2;
return dateString2;
}
I am trying to get the time from a string that looks like #"2016-05-12T16:25:55.000Z". I have tried something like this:
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = #"HH:mm";
formatter.timeZone = [NSTimeZone systemTimeZone];
NSDate *serverDate = [formatter dateFromString:dateString];
NSString* time = [formatter stringFromDate:serverDate];
NSLog(#"Time: %#", time);
But my serverDate is returning null. I'm not sure what I am doing wrong.
When you create an NSDate from an NSString, the date format has to completely match the entire string.
But it seems your goal is to get the time as a string. So just get the substring:
NSString *time = [dateString substringWithRange:NSMakeRange(11, 5)];
Of course this doesn't deal with the timezone in any way. If you wish to parse the original string into an NSDate and then get the time from that date, all with needed timezone adjustments, then you need two date formats. One to parse the original string into an NSDate, and the 2nd (the one you already have), to generate the new string with the desired output (the time in this case).
You can set the dateFormat property of your formatter to: #"yyyy-MM-dd'T'HH:mm:ssZ", and then get the time value using NSDateComponents.
First convert your date to NSDate
+ (NSDate *) convertDateToNSDateWithGivenFormat: (NSString *) dateStr Format:(NSString*) format
{
NSDateFormatter *dateFormatterDate = nil;
NSDate *dateonly = nil;
if (dateFormatterDate == nil) {
dateFormatterDate = [[NSDateFormatter alloc] init];
[dateFormatterDate setDateFormat:format];
}
dateonly = [dateFormatterDate dateFromString:[NSString stringWithFormat:#"%#", dateStr]];
return dateonly;
}
then use the NSDate variable to split date and time
+ (NSString *) GetFormattedTimeStringForGivenDate:(NSDate *) date
{
NSString *retStr = nil;
NSDate *now = date;
NSDateFormatter *dateFormatterDateOnly = nil;
NSDateFormatter *dateFormatterTimeOnly = nil;
if (dateFormatterDateOnly == nil) {
dateFormatterDateOnly = [[NSDateFormatter alloc] init];
[dateFormatterDateOnly setDateFormat:#"MM/dd/yyyy"];
}
if (dateFormatterTimeOnly == nil) {
dateFormatterTimeOnly = [[NSDateFormatter alloc] init];
[dateFormatterTimeOnly setDateFormat:#"hh:mm:ss:a"];
}
//if you need date use this
//retStr = [NSString stringWithFormat:#"%#", [dateFormatterDateOnly stringFromDate:now]];
retStr = [NSString stringWithFormat:#"%#", [dateFormatterTimeOnly stringFromDate:now]];
return retStr;
}
Here is example. You can change the Format as per your need:
NSDate *myDt = [MyClass convertDateToNSDateWithGivenFormat: #"2016-05-12T16:25:55" Format:#"yyyy-MM-dd'T'HH:mm:ss"];
NSString *str = [MyClass GetFormattedTimeForGivenDate:myDt];
In Objective C, we could easily assign present date to NSString like string = [NSDate date];.
Could someone help me how to assign the same in Swift ? Thanks in advance.
First off, your statement...
In Objective C, we could easily assign present date to NSString like string = [NSDate date];
Is complete rubbish.
In Objective-C you need to use an NSDateFormatter to render an NSString out of an NSDate.
You would do it something like this...
NSDate *date = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle
NSString *string = [df stringFromDate:date];
Now, in Swift, not surprisingly, it is EXACTLY the same.
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
let string = dateFormatter.stringFromDate(date)
maybe you want this:
let string = NSDate().description
I have a NSString and I need to check that it is in a this specific format MM/DD/YY. I then need to convert that to a NSDate. Any help on this would be much appreciated. Sidenote - I have searched around and people suggest using RegEx, I have never used this and am unclear about it generally. Can anyone point me to a good resource/explanation.
NSString *strDate1 = #"02/09/13";
NSString *strDate2 = #"0123/234/234";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"GMT"]];
NSDate *dateFormat1 = [dateFormatter dateFromString:strDate1];
NSDate *dateFormat2 = [dateFormatter dateFromString:strDate2];
NSLog(#"%#", dateFormat1); // prints 2013-09-02 00:00:00 +0000
NSLog(#"%#", dateFormat2); // prints (null)
So you will know when it's not formatted correctly if the NSDate is nil. Here's the link to the docs if you need more info: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1
Use an NSDateFormatter for both tasks. If you can convert the string to a date then it is in the correct format (and you already have the result).
I know that this is a late answer, but it is impossible to always guarantee that a string is in this particular date format.
A date formatter, a regex, or even a human can not verify certain dates, because we don't know if the user is entering "mm/DD/yy" or "DD/mm/yy". It is common in some places to enter the day of the month first, while in other areas you enter the month first. So if they enter "09/06/2013" do they mean "September 6th" or the "9th of June"?
Here is a simple function for anyone searching for a simple solution.
- (BOOL) isTheStringDate: (NSString*) theString
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:theString];
if (dateFromString !=nil) {
return true;
}
else {
return false;
}
}
You have to change the formatter below to match the formatting your date is using.
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
I would like to compare the current date with another date, and if that is date is earlier than the current date, then I should stop the next action. How can I do this?
I have todays date in yyyy-MM-dd format. I need to check this condition
if([displaydate text]<currentdate)
{
//stop next action
}
Here if displaydate is less than todays date then it has to enter that condition.
NSDate *today = [NSDate date]; // it will give you current date
NSDate *newDate = [dateFormatter dateWithString:#"xxxxxx"]; // your date
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
result = [today compare:newDate]; // comparing two dates
if(result==NSOrderedAscending)
NSLog(#"today is less");
else if(result==NSOrderedDescending)
NSLog(#"newDate is less");
else
NSLog(#"Both dates are same");
got your solution from this answer How to compare two dates in Objective-C
Alternative to #NNitin Gohel's answer.
Compare using NSTimeInterval ie NSDate timeIntervalSince1970:
NSTimeInterval *todayTimeInterval = [[NSDate date] timeIntervalSince1970];
NSTimeInterval *previousTimeInterval = [previousdate timeIntervalSince1970];
if(previousTimeInterval < todayTimeInterval)
//prevous date is less than today
else if (previousTimeInterval == todayTimeInterval)
//both date are equal
else
//prevous date is greater than today
You can have a closer look at this Tutorial about NSDateFormatter and when you have your NSDate object you can compare it to another NSDate and get an NSTimeInterval which is the difference in seconds.
NSDate *nowDate = [NSDate date];
NSTimeInterval interval = [nowDate timeIntervalSinceDate:pastDate];
Some methods of NSDate class are:
isEarlierThanDate. // using this method you can find out the date is previous or not..
isLaterThanDate
minutesAfterDate.
minutesBeforeDate. etc..
also see this link with many methods of NSDate in iPhone SDK..
how-to-real-world-dates-with-the-iphone-sdk
Update
//Current Date
NSDate *date = [NSDate date];
NSDateFormatter *formatter = nil;
formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
use this bellow method for convert NSString date to NSDate format just paste this method in your.m file
- (NSDate *)convertStringToDate:(NSString *) date {
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:#"yyyy-MM-dd"];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", date);
date = [date stringByReplacingOccurrencesOfString:#"+0000" withString:#""];
nowDate = [formatter dateFromString:date];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", nowDate);
return nowDate;
}
after that when you want to use it just use like bellow..
NSDate *tempDate2 = [self convertStringToDate:yourStringDate];
and then try to compare like this..
if (tempDate2 > nowDate)