I'm trying to get the local time from an NSDate and it is only outputting the +0000 timezone. I'm parsing the information from an ICS file and then converting the string (looks like 20131001T114445Z) to a date with NSDateFormatter but for some reason I can't change it to the user's local time.
Here is the relevent code -
+(ISParseICS*) icsParser
{
if( !fetcher ) {
fetcher = [ISParseICS new];
fetcher.dateFormatter = [[NSDateFormatter alloc] init];
[fetcher.dateFormatter setDateFormat:#"yyyyMMdd HHmmss"];
NSLog(#"Created new singleton fetcher");
}
return fetcher;
}
Code below within -(NSMutableArray *)fetchPassesSync
// Extract date/time
NSString *unformattedEndDateTimeString;
NSDate *endDate;
eventScanner = [NSScanner scannerWithString:event];
[eventScanner scanUpToString:#"DTEND:" intoString:nil];
[eventScanner scanUpToString:#"\n" intoString:&unformattedEndDateTimeString];
unformattedEndDateTimeString = [unformattedEndDateTimeString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:#"DTEND:"] withString:#""];
NSLog(#"This is unformattedEndDateTimeString: %#", unformattedEndDateTimeString);
endDate = [self dateFromString:unformattedEndDateTimeString];
NSLog(#"End date - %#", endDate);
...and the last piece:
-(NSDate *)dateFromString:(NSString *)dateString {
dateString = [dateString stringByReplacingOccurrencesOfString:#"T" withString:#" "];
dateString = [dateString stringByReplacingOccurrencesOfString:#"Z" withString:#""];
NSDate *date = [self.dateFormatter dateFromString:dateString];
// NSLog(#"The output date: %#", date);
return date;
}
I'm pretty new to programming and I hope I asked the question correctly. Thanks in advance.
Edit: What I get out of all this code is it takes the string "20131001T114445Z" and outputs like this "2013-10-01 11:44:45 +0000"
Try this:-
NSString *dateStr = #"20131001T114445Z";
// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[dateFormat setDateFormat:#"yyyyMMdd'T'hhmmss'Z'"];
NSDate *date = [dateFormat dateFromString:dateStr];
// Convert date object to desired output format
[dateFormat setDateFormat:#"yyyy-MM-dd hh:mm:ss Z"];
dateStr = [dateFormat stringFromDate:date];
NSLog(#"%#",dateStr);
[dateFormat release];
Related
In iPhone Device, getting wrong DateTime Format for customer device from our Production App.
we using DateTime format as yyyy-MM-dd HH:mm:ss and replace empty with T
and excepted result as 2018-07-13T15:07:36, but getting date time as 2018-07-13T3:07:36TPM
Steps to Reproduce:
Method to get DateTime String
+ (NSString *)getCurrentLocalDateTime
{
NSDate *localDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:localDate];
dateString = [dateString stringByReplacingOccurrencesOfString:#" " withString:#"T"];
NSLog(#"CURR: %#", dateString);
return dateString; // yyyy-MM-ddTHH:mm:ss
}
Expected Results:
Output Data must be - 2018-07-13T15:07:36
Actual Results:
Actual Data - 2018-07-13T3:07:36TPM
issue happend in iOS Version - 11.3.1 and 11.1.2
Just insert the T wrapped in single quotes into the date format to get the literal "T"
#"yyyy-MM-dd'T'HH:mm:ss"
According to Technical Q&A QA1480 for fixed-format dates set the locale of the date formatter to the fixed value en_US_POSIX:
+(NSString *)getCurrentLocalDateTime
{
NSDate *localDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:localDate];
NSLog(#"CURR: %#", dateString);
return dateString; // yyyy-MM-ddTHH:mm:ss
}
Following is the example of NSDateFormatter. You can use it and customise it's order of day:month:year
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm"];
NSDate *currentDate = [NSDate date];
NSString *dateString = [formatter stringFromDate:currentDate];
Facebook provides date objects in the format: 2010-12-01T21:35:43+0000
I want to convert this format to NSDate.
I am using the following code. Why does it return null.
NSDateFormatter *df = [[NSDateFormatter alloc] init];
dateString = [dateString stringByReplacingOccurrencesOfString:#"T" withString:#" "];
dateString = [dateString stringByReplacingOccurrencesOfString:#"+" withString:#" +"];
NSLog(#"%#", dateString);
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss '+'ZZZZ"];
NSLog(#"%#",df.dateFormat);
NSDate *date = [df dateFromString:dateString];
NSLog(#"%# date",date);
Just replace '+'ZZZZ with +zzzz in your code..
NSString *dateString=#"2010-12-01T21:35:43+0000";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
dateString = [dateString stringByReplacingOccurrencesOfString:#"T" withString:#" "];
dateString = [dateString stringByReplacingOccurrencesOfString:#"+" withString:#" +"];
NSLog(#"%#", dateString);
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss +zzzz"];
NSLog(#"%#",df.dateFormat);
NSDate *date = [df dateFromString:dateString];
NSLog(#"%# date",date);
Output is :
2016-04-30 14:52:10.118 date[2523:187669] 2010-12-01 21:35:43 +0000
2016-04-30 14:52:10.120 date[2523:187669] yyyy-MM-dd HH:mm:ss +zzzz
2016-04-30 14:52:10.153 date[2523:187669] 2010-12-01 21:35:43 +0000 date
You don't need to replace any character in string
Try out this code:
Objective-C
NSString *dateString=#"2010-12-01T21:35:43+0000";
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
NSDate *date = [df dateFromString:dateString];
NSLog(#"%# date",date);
Swift:
let dateString: String = "2010-12-01T21:35:43+0000"
let df: NSDateFormatter = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
let date: NSDate = df.dateFromString(dateString)!
print("date: \(date)")
Just use yyyy-MM-dd'T'HH:mm:ssZ for your dateFormat and don't mess around with the string manipulation at all.
The only thing you might want to do is set the locale as outlined in Apple's Technical Q&A 1480, so that this will work regardless of what sort of calendar settings the device might otherwise have:
df.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
It is too much confusing and i have pasted my code below.
I have a eopoc time.
// Function that converts eopc to NSString
NSString * ConvertEpocToDateStr(NSString *epoc)
{
NSString *res;
NSTimeInterval sec = [epoc doubleValue]/1000.0;
NSDate *eDate = [[NSDate alloc] initWithTimeIntervalSince1970:sec];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd hh:mm a"];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"IST"];
NSLog (#" Time in your Zone is %# ", [[dateFormatter timeZone] description]);
res = [dateFormatter stringFromDate:eDate];
return res;
}
// From NSString to back NSDate.
NSDate * backToDate (NSString * dInStr )
{
NSDateFormatter *dFormatter = [[NSDateFormatter alloc] init];
[dFormatter setDateFormat:#"MM/dd hh:mm a"];
dFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"IST"];
NSDate *FromString = [dFormatter dateFromString:dInStr];
return dFromString;
}
And, I tried to print below .
epoc -> 1397600251077
ConvertEpocToDateStr -> 04/16 03:47 am
backToDate -> 2000-04-15 22:17:00 +0000
Both should be same right? I am not sure where/what i am missing?
Of course, you get the same dates. IST is 5.30 h ahead of GMT+0.
Since you drop out year in your direct formatter and use the date time string without the year
by default it is set to 2000.
Evidently, 2000-04-15 22:17:00 +0000 is the same as 2000-04-16 03:47:00 +0530.
This question already has answers here:
Objective-C String(yyyy-mm-dd) to NSDate
(3 answers)
Closed 9 years ago.
I get null date even when the string that I pass has a date as shown below:-
Generic input Date Format is "MM/dd/YYYY hh:mm a"
NSString input Date can be one of the following: "12/1/2012" , "12/1/2012 01:43 am" , "01:43 am"
Expected output which I am trying is that , it must print date if it exists in input string and time must be printed out if it exists in the input string.
Input:-
[self testDate:#"12/1/2012"]
Code:-
-(void) testDate:(NSString*) str{
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy hh:mm a"];//My Generic Date Format
self.dateTest=[formatter dateFromString:str];
[self printDate:self.dateTest];
}
-(void) printSeparatedDateAndTime:(NSDate*) date{
NSDateFormatter *dateF=[[NSDateFormatter alloc] init];
[dateF setDateFormat:#"MM/dd/yyyy"];
NSString *dateStr=[dateF stringFromDate:date];
NSLog(#"Date= %#",dateStr);
[dateF setDateFormat:#"hh:mm a"];
NSString *timeStr=[dateF stringFromDate:date];
NSLog(#"Time= %#",timeStr);
}
Output Date:-
Date= (null)
Time= (null)
Input can be in any format, ex
input
"12/1/2012"
output
date="12/1/2012"
time=null
input
"12/1/2012 01:43 am"
output
date="12/1/2012"
time=01:43 am
input
"01:43 am"
output
date=null
time="01:43 am"
One can get a different answer here Objective-C String(yyyy-mm-dd) to NSDate. This refers to answer if date format set is wrong.
In my case date format is correct. But it might have only date, only time or both of them.
To separate date and time from a String one can refer here ios4 - splitting a date and time from a string into two separate strings, but it does not have a checked answer or a valid answer.
Remove hh:mm a and the format can be either "MM/dd/yyyy" or "dd/MM/yyyy".
-(void) testDate:(NSString*) str{
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy"];
self.dateTest=[formatter dateFromString:str];
[self printDate:date];
}
Your printeDate: will not work as expected since the date created don't have any information about the time and you are trying to show hours and minutes.It will always show 12.00 AM.
If you want to show hours and minutes you need to include that also in your input string.
EDIT : Since dateFormats can be in three formats you need to do a trial and error.
-(void) testDate:(NSString*) str{
NSArray *dateFormats = #[#"dd/MM/yyyy",#"hh:mm a",#"dd/MM/yyyy hh:mm a"];
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
NSDate *date = nil;
for (NSString *dateFormat in dateFormats) {
[formatter setDateFormat:dateFormat];
date = [formatter dateFromString:str];
if (date) {
break;
}
}
[self printDate:date];
}
OR
-(void) testDate:(NSString*) dateString
{
NSDate *date = nil;
NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeDate
error:&error];
NSArray *matches = [detector matchesInString:dateString
options:0
range:NSMakeRange(0, [dateString length])];
for (NSTextCheckingResult *match in matches) {
if (match.date) {
date = match.date;
break;
}
}
[self printDate:date];
}
EDIT 2 : As it is a requirement to have data/time to nil out. Please try
typedef enum {
ValidDateType = 0,
ValidTimeType = 1,
ValidDateTimeType =2
}ValidType;
- (void)testDate:(NSString*) dateString
{
NSArray *dateFormats = #[#"dd/MM/yyyy",#"hh:mm a",#"dd/MM/yyyy hh:mm a"];
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
__block NSDate *date = nil;
__block ValidType type = ValidDateType;
[dateFormats enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *dateFormat = (NSString *)obj;
[formatter setDateFormat:dateFormat];
date = [formatter dateFromString:dateString];
if (date) {
type = idx;
*stop = TRUE;
}
}];
[self printDate:date validType:type];
}
- (void)printDate:(NSDate*) date validType:(ValidType)type
{
NSDateFormatter *dateF=[[NSDateFormatter alloc] init];
[dateF setDateFormat:#"MM/dd/yyyy"];
NSString *dateStr=[dateF stringFromDate:date];
[dateF setDateFormat:#"hh:mm a"];
NSString *timeStr=[dateF stringFromDate:date];
dateStr = (type == ValidTimeType)?nil:dateStr;
timeStr = (type == ValidDateType)?nil:timeStr;
NSLog(#"Time= %#",timeStr);
NSLog(#"Date= %#",dateStr);
}
You set the date format to include time: MM/dd/yyyy hh:mm a, but you are not passing any time with you string: 12/1/2012.
Just remove the hh:mm a from the date format :
-(void) testDate:(NSString*) str{
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
self.dateTest = [formatter dateFromString:str];
[self printDate:self.dateTest];
}
Also I would suggest not using a static date format, just incase you have any non America users. Apple has added NSDateFormatterStyle to make it easy for you to use the user/system selected style of formatting.
-(void) printDate:(NSDate*) date{
NSDateFormatter *dateF=[[NSDateFormatter alloc] init];
dateF.dateStyle = NSDateFormatterMediumStyle;
dateF.timeStyle = NSDateFormatterNoStyle;
NSString *dateStr=[dateF stringFromDate:date];
NSLog(#"Date= %#",dateStr);
dateF.dateStyle = NSDateFormatterNoStyle;
dateF.timeStyle = NSDateFormatterShortStyle;
NSString *timeStr=[dateF stringFromDate:date];
NSLog(#"Time= %#",timeStr);
}
In my project i need to check some format coming from server, So i want to write a regular expression to check the format.
This is the format "03/31/2013 08:00:00" and other format is "03/31/2003 08:00 AM/PM"
How can i check this date formats. Can any one help me.
Regards
Kiran
^(?:\d{2}\/){2}\d{4} \d{2}:\d{2}(?::\d{2}| (?:AM|PM))?$
Note that it won't check for incorrect values.
If you want to get NSDate from this string, you should use NSDateFormetter instead:
NSString * date = #"03/31/2013 08:00:00"; // source string
NSDateFormatter * date_formatter = [[NSDateFormatter alloc] init];
[date_formatter setDateFormat: #"MM/dd/yyyy HH:mm:ss"]; // your date format
NSDate * result = [date_formatter dateFromString: date]; // converting
NSLog (#"%#", [result description]); // log your date result
[date_format release];
Not a real answer to your question about regex but, if you want to get the date from the dateString received from server you can try a trial and error method with the dateFormat of NSDateFormatter.
NSString *dateFormat1 = #"MM/dd/yyyy HH:mm:ss";
NSString *dateFormat2 = #"MM/dd/yyyy hh:mm:ss a";
NSString *dateString = #"03/31/2013 08:00:00 AM";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
[dateFormatter setDateFormat:dateFormat1];
NSDate *date = [dateFormatter dateFromString:dateString];
if (!date) {
[dateFormatter setDateFormat:dateFormat2];
date = [dateFormatter dateFromString:dateString];
}
NSLog(#"Date : %#",date);