Convert String to Date in Objective-C [duplicate] - ios

This question already has an answer here:
Converting NSString to NSDate - wrong format
(1 answer)
Closed 4 years ago.
How do i convert string to date in Objective C.
I have tried the following but did not figure it out.
NSString *str = #"3/2/2018 11:44:32 AM";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/d/yyyy h:mm:ss a"];
NSDate *resultDate = [[NSDate alloc] init];
resultDate = [df dateFromString:str];
NSLog(#"result date: %#", resultDate);
result date: 2018-03-02 06:14:32 +0000 ,but i need to get it as
result date: 3/2/2018 11:44:32 AM

You are correctly parsing the string to the Date object. The way it is presented by the print is because by default if printing an object, its description is printed. In case of Date, it will be always the format you get. But the date is correct.
If you want to get it presented the way it was before, again use the same dateFormatter and just format the date to string back:
NSLog(#"result date: %#", [df stringFromDate:resultDate]);
UPDATE
If the problem is the hour shift, that's due to your current timezone that will be used when parsing using DateFormatter. To overcome this, set explicitly timezone and locale of the date formatter, see this example (swift version, but you need just those two line with setting timeZone and locale on dateFormatter):
let dateString = "3/2/2018 11:44:32 AM"
let df = DateFormatter()
df.dateFormat = "MM/d/yyyy h:mm:ss a"
// set the timezone and locale of the dateformatter:
df.timeZone = TimeZone(identifier: "GMT")
df.locale = Locale(identifier: "en_US_POSIX")
let date = df.date(from: dateString)
// now it will print as you expect:
print(date)

Your issue is related to your app current locale, if your current locale is "en_US" then your NSLog(#"result date: %#", resultDate); line will print
result date: Fri Mar 2 11:44:32 2018

Maybe, this code will help you, again that date its convert to Nsstring, check it this code
-(void)DateChange
{
NSString *Input_Date =#"3/22/2018 11:44:32 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"M/d/yyyy hh:mm:ss a"];
NSDate * Format_date = [dateFormatter dateFromString:Input_Date];
[dateFormatter setDateFormat:#"M/d/yyyy hh:mm:ss a"];
NSString *Change_date = [dateFormatter stringFromDate:Format_date];
NSLog(#"Final Change Date :- %#",Change_date);
}
My Output is :-
Final Change Date :- 3/22/2018 11:44:32 AM

Related

NSDate from String returning nil

I am storing dates as strings in the format: 2018-07-10 21:00:29 +0000
I created a formatter to convert the strings back into dates:
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
[formatter setLocale:[NSLocale currentLocale]];
NSDate *date = [formatter dateFromString:[chore getDate]];
However, the date that is returned is always nil. Does anyone know what I'm doing wrong?
You set the wrong format in the dateformat. So it will always return the nil value.
The following method can return the date in the NSDate format.
-(NSDate *)convertDate :(NSString *)date1 //the argument date1 is the string date you used
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
formatter.dateFormat = #"yyyy-MM-dd HH:mm:ss Z"; // the format which you used in the string date
[formatter setLocale:[NSLocale currentLocale]]; //This for set the Locale .It is not compulsory.
NSDate *date = [formatter dateFromString:date1];
return date;
}
Refer to date formatter date formats here:
You need to update your date format to something like:
"yyyy-MM-dd HH:mm:ss Z"

Convert date string into proper format

I am getting a response from a server and there is a date string I need to convert into a date:
Thu Jun 29 07:15:25 +0000 2017
I am trying to convert the string into a human readable format. Can anyone suggest how to convert this string into date?
You need to parse the date string into a Date object using a DateFormatter, then create a string from that Date using another DateFormatter with the output format you want to use.
let created_at = "Thu Jun 29 07:15:25 +0000 2017"
let df = DateFormatter()
df.dateFormat = "E MMM dd HH:mm:ss Z yyyy"
guard let date = df.date(from: created_at) else {return}
let outputFormatter = DateFormatter()
outputFormatter.dateFormat = "EEE, MMM d"
let outputDate = outputFormatter.string(from: date)
If you want to know what date formats look like, use NSDateFormatter.com, which has an interactive interface where you can play around with different date formats and have examples of most common formats as well.
This is how you can format it in "Thu Jun 29"
-(NSString *)formatCreatedAt:(NSString *)createdAt
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"EEE MMM dd HH:mm:ss Z yyyy"];
NSDate *date = [dateFormat dateFromString:createdAt];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE MMM dd"];
NSString *stringFromDate = [formatter stringFromDate:date];
return stringFromDate;
}
Pass the value of created_at in this method and the output will be returned in your specified format.

how to show time 08:00:00 to 8 am using swift

I'm receiving time in string as 08:00:00 and I need to show it as 8 am.
I have no idea how to do it so guys help me.
I don't know how to do it using NSDate.
do like
Objective-C
NSString *sample = #"08:00:00";
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"]; // or use hh:mm:ss
NSDate *date1 = [dateFormatter dateFromString:sample];
[dateFormatter setDateFormat:#"HH a"]; // or use hh
NSString *finaldate = [dateFormatter stringFromDate:date1];
NSLog(#"%#",finaldate);
Swift
var sample: String = "08:00:00"
var dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss" // or use hh:mm:ss
var date1: NSDate = dateFormatter.dateFromString(sample)
dateFormatter.dateFormat = "HH a" // or use hh
var finaldate: String = dateFormatter.stringFromDate(date1)
NSLog("%#", finaldate)
Time Format
// 24 hours fomat
HH -- 13, 14, etc
// 12 hours format
hh -- 01, 02, etc

On setting doesRelativeDateFormatting = YES, stringFromDate returns nil

In the NSDateFormatter documentation,
If a date formatter uses relative date formatting, where possible it replaces the date component of its output with a phrase—such as “today” or “tomorrow”—that indicates a relative date.
I am using the following code:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:#"EEEE dMMMM',' hma"
options:0
locale:[NSLocale currentLocale]];
formatter.doesRelativeDateFormatting = YES;
NSLog(#"Date: %#", [formatter stringFromDate:[NSDate date]]);
It logs Date:.
But on commenting out formatter.doesRelativeDateFormatting = YES; the output comes out correct.
Date: Tuesday, 19 August 1:18 pm
Am I understanding doesRelativeDateFormatting wrong?
Hi when i modified code like this. it works..
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:#"EEEE dMMMM',' hma"
options:0
locale:[NSLocale currentLocale]];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
formatter.doesRelativeDateFormatting = YES;
NSLog(#"Date: %#", [formatter stringFromDate:[NSDate date]]);
It seems like doesRelativeDateFormatting doesn't work with a custom dateFormat.
I had the same challenge as you to display Today, 11:44 pm or 19 Aug, 1:23 am. The hard part being that the year was to be always excluded.
I solved it like this:
Get a formatted date any style you like, with doesRelativeDateFormatting enabled
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.doesRelativeDateFormatting = true
var dateString = dateFormatter.stringFromDate(dateToFormat)
Get the formatted year from the same date (make sure the dateFormat has the correct number of y's to represent the year. I use 4 y's because the Medium date style uses the full year format.
let yearFormatter = NSDateFormatter()
yearFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("yyyy", options: 0, locale: NSLocale.currentLocale())
let yearString = dateFormatter.stringFromDate(dateToFormat)
Finally compose the final string by removing the year from the generated dateString and trimming some excess white space.
var finalString = dateString.stringByReplacingOccurrencesOfString(yearString, withString: "")
finalString = finalString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
It's not an ideal solution because I'm sure there will be some locale where the year is formatted right between the day and month or something, which would create a funky looking string. But it works in all my tested cases.

NSDateFormatter not Working for Twitter date

I am trying to format a date i am getting from twitter using the STTwitter library.
However the code that I've tried so far has not worked.
Code for getting the date from twitter:
NSString *dateString = [status valueForKey:#"created_at"];
This returns the time, date, time zone and year in which the tweet was made which looks messy.
I tried using the following code to convert this and make it neater:
NSDateFormatter *dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"MMddHHmm"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
NSLog(#"%#", dateFromString);
dateFormatter =[[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd MMMM' at 'hhmm a"];
NSString *mydate=[dateFormatter stringFromDate:dateFromString];
And then try to put the result in a text label:
cell.detailTextLabel.text = my date;
Ive tried many different variations of the Date Formatter but none have worked and i have no idea why.
Thanks for your help :)
The date format you are using is not even close the date string used in the result, which is something like Fri Nov 18 20:35:49 +0000 2011.
NSString *dateStr = #"Fri Nov 18 20:35:49 +0000 2011";
NSDateFormatter *dateFormatter= [NSDateFormatter new];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setDateFormat:#"EEE MMM dd HH:mm:ss Z yyyy"];
NSDate *date = [dateFormatter dateFromString:dateStr];
The real trick is in the locale used, since the date is localized in english.
STTwitter has a category for that:
NSString *s = [tweet valueForKey:#"created_at"];
NSDate *date = [[NSDateFormatter stTwitterDateFormatter] dateFromString:s];
I created a gist with Swift implementation of it:
https://gist.github.com/appzzman/62339fcd10bbe8fce256 It takes Twitter date and lets you specify the output format of the date.
import UIKit
func parseTwitterDate(twitterDate:String, outputDateFormat:String)->String?{
let formatter = NSDateFormatter()
formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
var indate = formatter.dateFromString(twitterDate)
var outputFormatter = NSDateFormatter()
outputFormatter.dateFormat = "hh:mm a dd:MM:yy"
var outputDate:String?
if let d = indate {
outputDate = outputFormatter.stringFromDate(d)
}
return outputDate;
}
var str = "Wed Sep 02 19:38:03 +0000 2009"
var outputDateFormat = "hh:mm a dd:MM:yy"
parseTwitterDate(str, outputDateFormat)

Resources