NSString *nameToSave = word;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *fromDateString=[dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
nameToSave = [word stringByAppendingString:fromDateString];
nameToSave = [nameToSave stringByAppendingString:#".txt"];
NSLog(#"Server notes name .............>>>>>>!!!! %#",nameToSave);
for saving filenames i am using dateformatter, my problem is in the above code word is same for two files and it is run within one second then two file names are same. So the files are overriding.., i think with use of milliseconds i can solve my problem, But i don't know how to get current time in milliseconds. [ seconds/1000 or any arithmetic operations is not helpful for me..., because after applying arithmetic operation also we get same name]
You can set a date format like
[dateFormatter setDateFormat:#"yyyy-MM-dd-HH:mm:ss:SSS"];
"SSS" is for milliseconds.
just do like this [[NSDate date] timeIntervalSince1970];
Related
Sometimes my code is returning an a.m. or p.m. but not always. Most of the time it just returns what I expect, which is something like: 20110815170852164
But other times it's returning: 20100412010241 a.m.450
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyyMMddHHmmssSSS"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
What could be causing this? Specific date/time country settings on users iPhones? I have this out to thousands of people, and most aren't returning the a.m. (which is expected) but others are. WHY?
The problem you are describing is a known bug. Check out some discussion on the problem on stackoverflow, and you can find some possible work-arounds there.
Here's an excerpt of huyz's explaination of the bug:
The problem comes from NSDateFormatter somehow “getting stuck” in the 12 or 24-hour time mode that the user has manually selected. So if a French user manually selects 12-hour mode, and the application requested NSDateFormatter to output time with the 24-hour format “HHmm”, it would actually receive time in a 12-hour format, e.g. “01:00 PM”, as if the application had instead requested “hhmm aa”. The reverse would happen if a US user manually selected 24-hour mode: outputting time with the 12-hour format “hhmm aa” would actually get you time in the 24-hour format instead, e.g. “17:00″.
Right. The solution is to explicitly set the locale of the date formatter, ideally to en_US_POSIX. See the final answer to this question.
I was working on a data-share function of a project which was highly depending on the values/results entered in advance when I bumped into the same problem. I implemented a nasty little workaround for saving the right datetime in 24h format to the database.
The solution is very simple
First, I get the local date from the device:
NSDate* now = [NSDate date];
Second step is to create a NSDateFormatter with US locale regardless of system's locale to make sure that "PM" is going to be "PM":
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]];
Then, I get the date (year, month, day) into a string:
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString *date = [formatter stringFromDate:now];
For the next part, I get the hours, minutes and seconds:
[formatter setDateFormat:#"hh"];
NSString *hours = [formatter stringFromDate:now];
[formatter setDateFormat:#"mm"];
NSString *minutes = [formatter stringFromDate:now];
[formatter setDateFormat:#"ss"];
NSString *seconds = [formatter stringFromDate:now];
Next, I get the part of the day:
[formatter setDateFormat:#"a"];
NSString *partOfDay = [formatter stringFromDate:now];
Then comes the logic: if the part of the day is PM but the hours are less then 12, we just have to correct that. In code:
if([partOfDay isEqualToString:#"PM"] && [hours intValue] < 12) {
hours = [[NSString alloc] initWithFormat:#"%i", ([hours intValue] + 12)];
}
After this modification, we are ready to put the string together in order to have a datetime ready to be saved into SQL:
NSString *sqlDateTime = [[NSString alloc] initWithFormat:#"%# %#:%#:%#", date, hours, minutes, seconds];
That's all there is to it. And from now we can only hope that Apple is going to fix this bug to make it work as it should be.
I hope this helps.
I've searched and haven't found an exact question like mine, so here goes nothing:
I have a NSString containing a key that I pull from an XML feed. The key is a time in 24-hour format (e.g. 13:30 or 15:00.) I'd like to convert the NSString to an NSDate and have it converted to the appropriate timezone based on the device's set timezone. The key is Unicode HH:mm (24:00), so I'm curious why this does not work as it should.
I've already gotten a basic outline that should work, but alas does not. The 2nd NSLog (Got NS Date) returns null and the final log returns a strange number (1969-12--2147483629 -596:-31:-23 +0000 to be precise.) What am I doing wrong here?
Thanks in advance,
NSString *dateString = [dict objectForKey:#"24hrdate"];
NSLog(#"NSString Date: %#", dateString);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm"];
NSDate *sourceDate = [formatter dateFromString:dateString];
NSLog(#"Got NS Date: %#", sourceDate);
NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone *destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
NSLog(#"Final Date: %#", destinationDate);
First of all understand that the date component will be 01-01-1970 because it isn't provided. I am assuming that you want the time to be 04:00 GMT if the input string is #"04:00". That you can achieve by setting the time zone of the formatter.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
[formatter setDateFormat:#"HH:mm"];
NSDate *sourceDate = [formatter dateFromString:dateString];
NSDate is used to represent a date and time. While you can represent just a date by sticking with midnight, you can't really represent just a time of day with it. You can sort of fake this on the Mac (it defaults to some reasonable day), but on iOS you'll get wildly inaccurate times instead. (At least, you do on certain versions. This may have been fixed.)
There's two approaches here:
You can build a NSDateComponents from your time of day and using dateByAddingComponents to add that to midnight on the date you want the time to appear on. This will fail to return the time you expect on a day where daylight savings begins or ends.
You can build a date/time string using the date you want (NSDate) and the time (likely, as a NSString).
- (NSDate *)timeInHours: (NSInteger)hours
minutes: (NSInteger)minutes
seconds: (NSInteger)seconds
onDate: (NSDate *)inDate;
{
id timeStr = [[NSMutableString alloc] initWithFormat: #"%02d:%02d:%02d", hours, minutes, seconds];
id dateStr = [dateWithoutTimeFormatter stringFromDate: inDate];
id dateTimeStr = [[NSString alloc] initWithFormat: #"%# %#", dateStr, timeStr];
[timeStr release];
id dateTime = [dateWithTimeFormatter dateFromString: dateTimeStr];
[dateTimeStr release];
return dateTime;
}
If you really want just the time of day, just keep it around as a string.
Just wanted to post back that I did manage to achieve what I initially set out to do without any issues. Basically, I had to convert the string to NSDate, run that NSDate through a NSDateFormatter (set to the time's original timezone--NSDateFormatter's setTimeZone was helpful), pull an NSDate out of that, and then run that through another NSDateFormatter for the device's timezone. I then converted the resulting NSDate back to NSString, and stuck it on a UILabel.
This solution seems to have worked quite well, as I've set my devices to various timezones, and the timezone change is still correct.
EDIT: this was important to included, too:
NSString *date…….
date = [date stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
I have a small IOS program and that get a time from a database server. I would like to convert that to the users localtime (I always know the timezone of the server).
I have been playing with replacing the hour piece of the string, but that seems like a bad idea.
In C# I would convert the string into a DateTime and add the hours in the diference between the server time and the localtime, but I simply cant figure out how to do that in ObjectiveC.
So could anyone give a few hints? The date/time string I get from the sever looks like this:
2011-02-27 12:10:02
I would convert the date from the string into and NSDate object using NSDateFormatter. The you can use the dateByAddingTimeInterval method to add in your hour. Also NSCalendar has more advanced functions for adding time intervals.
I believe this should work for local time:
NSDateFormatter *dateFormatter = [NSDateFormatter alloc] init];
NSLocale *serverLocale = [NSLocale alloc] initWithLocaleIdentifier:#"en_US"];//Change to Server Locale
[dateFormatter setLocale:serverLocale];
[serverLocale release];
[dateFormatter setDateFormat:#"YYYY-MM-DD HH:MM:SS"];
NSDate *date = [dateFormatter dateFromString:#"2011-02-27 12:10:02 "];
//Replace the locale below with what you need
NSString *dateString = [date descriptionWithLocale:[NSLocale currentLocale]];
[dateFormatter release];
textField.text = dateString;
The input string is '20100908041312'
the format is year,month,day,Hours,minutes,seconds,time zone
and I have ben trying to convert it to an NSDate with this: #"yyyyMMddHHmmsszz"
But NSDate is nil, anyone see what I'm doing wrong?
-(NSDate*)convertPDFDateStringAsDate:(NSString*) _string{
//20100908041312
//year month day Hours minutes seconds and time zone
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMddHHmmsszz"];
NSDate *date = [dateFormat dateFromString:_string];
//date is nil...
[dateFormat release];
return date;
}
EDIT: its the time zone breaking it
EDIT2: #"yyyyMMddHHmmssTZD" stops it returning nil, but dosnt pick the time zone correctly
EDIT3: This was the code I Used in the end...i found that the format changes from PDF to PDF so the code deals with the variations that i Found, in some cases this wont extract the Time Zone Properly.
-(NSDate*)convertPDFDateStringAsDate:(NSString*) _string{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSString * formatCheck = [_string substringToIndex:2];
if(![formatCheck isEqualToString:#"D:"])
{
NSLog(#"ERROR: Date String wasnt in expected format");
return nil;//return [NSDate date];
}
NSString * extract = [_string substringFromIndex:2];
//NSLog(#"DATESTRING:'%#'",extract);NSLog(#"DATELENGTH:%i",[extract length]);
if([extract length]>14)
{
[dateFormat setDateFormat:#"yyyyMMddHHmmssTZD"];
}
else
{
[dateFormat setDateFormat:#"yyyyMMddHHmmss"];
}
NSDate * date = [dateFormat dateFromString:extract];
[dateFormat release];
return date ;
}
It should follow the unicode standard for the setDateFormat: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
You should be able to set the timezone this way:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyyMMddHHmmss"];
//Optionally for time zone conversations
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
Alex
I recognize the posting is over a year old, but no time is too late for a better answer.
Since you specify the input string is an Adobe PDF date string, then the format should conform to the PDF specification, which per the spec is: YYYYMMDDHHmmSSOHH'mm (omitting the prefix D:).
Note your input string is 14 characters long and your NSDate format is 16 characters long, so the timezone isn't in your input string as stated.
Nonetheless, the real answer to your question is to use the Quartz 2D CGPDFString function:
CFDateRef CGPDFStringCopyDate (CGPDFStringRef string
);
The function returns a CFDateRef which has a toll-free bridge to NSDate, so you can pass the date read from a PDF to this function and easily get back an NSDate by casting.
"12" isn't a valid time zone for any of the Unicode date format patterns, so NSDateFormatter returns nothing. http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
You may have to use all but the last two digits, then set the time zone on your new NSDate object by translating Adobe's two-digit number to an appropriate time zone.
I have spent way too much time (over an hour) on what I though would be a two minute task.
On the iPhone:
NSString * dateString = #"2010-09-11T00:00:00+01:00";
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd'T'HH:mm:ssTZD"];
NSDate *date = [formatter dateFromString:dateString];
RESULT: date == nil
What am I missing!! (Besides my deadline)
Regards,
Ken
TZD isn't a defined formatter per the unicode spec. The document you've linked to elsewhere was a suggestion someone made to W3C, for discussion only. The unicode standard followed by Apple is a finished standard, from a different body.
The closest thing to what you want would be ZZZ (ie, #"YYYY-MM-dd'T'HH:mm:ssZZZ"), but that doesn't have a colon in the middle. So you'd need to use the string:
2010-09-11T00:00:00+0100
Rather than the one you currently have that ends in +01:00.
E.g. the following:
NSString * dateString = #"2010-09-11T00:00:00+0100";
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"%#", date);
Logs a valid date object, of 2010-09-10 23:00:00 GMT.
Tip: try using your formatter to convert from an NSDate object to a string, then see what you get. It's often easier to debug in that direction than the other.
Have you read this?
http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
That TZD at the end of your format string looks a bit dodgy.
I solved this issue using this code.