I have a date string of
"5:09 pm Wed Sep 2",which is coming from server.
when converting the string into NSDate.
"2000-09-02 17:09:00 +0000" but the year should have been "2015" like:
"2015-09-02 17:09:00 +0000"
Here is my code please let me know where is the problem
NSString *dateStr = #"5:09 pm Wed Sep 2";
// Convert string to date object
NSString *dateFormat= ([self hasAMPM])?#"hh:mm a EEEE MMM d":#"hh:mm a EEEE MMM d" ;
NSDate * date = [self toLocalTime:[self convertDateFromString:dateStr OutputFormat:dateFormat]];
///****
-(BOOL)hasAMPM{
NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:#"j" options:0 locale:[NSLocale currentLocale]];
NSRange containsA = [formatStringForHours rangeOfString:#"a"];
BOOL hasAMPM = containsA.location != NSNotFound;
return hasAMPM;
}
-(NSDate *)toLocalTime:(NSDate *)date
{
NSTimeZone *tz = [NSTimeZone systemTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: date];
return [NSDate dateWithTimeInterval: seconds sinceDate: date];
}
-(NSDate *)convertDateFromString:(NSString *)strDate OutputFormat:(NSString *)outPutFormat
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:outPutFormat];
NSDate *date1= [formatter dateFromString:strDate];
return date1;
}
Please help me to get out of this situation.
If you want to add the year in your date according to current date, this works for dates from 1970 onwards, haven't checked for beyond that:
NSString *dateStr = #"5:09 pm Wed Sep 2";
NSString *dateString = [dateStr stringByAppendingString:#" 1970"];
// Convert string to date object
NSString *dateFormat= ([self hasAMPM])?#"hh:mm a EE MMM d yyyy":#"hh:mm a EE MMM d yyyy" ;
NSDate * date = [self toLocalTime:[self convertDateFromString:dateString OutputFormat:dateFormat]];
NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
greCalendar.timeZone = [NSTimeZone systemTimeZone];
NSDateComponents *componenetsForCurrent = [greCalendar componentsInTimeZone:[NSTimeZone systemTimeZone] fromDate:[NSDate date]];
NSInteger year = componenetsForCurrent.year;
NSDate *requiredDate = [greCalendar dateByAddingUnit:NSCalendarUnitYear value:(year-1970) toDate:date options:NSCalendarWrapComponents];
You can split your date using NSDateComponents, and work with year independently
NSDateComponents *dateComponents = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:date];
[dateComponents setYear:someYear];
date = [calendar dateFromComponents:dateComponents];
Related
I have dateString with this format "mm/dd/yyyy '-' HH:mm".
I want to extract the date in string and hour in string.
I've tried the following code but this return a wrong date:
- (void) extractDate: (NSString *)dateString intoHour: (NSString *)hourLabel and: (NSString*)dateLabel {
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:#"mm/dd/yyyy '-' HH:mm"];
NSData *date = [formatter dateFromString:dateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:date];
hourLabel = [NSString stringWithFormat:#"%lu:%lu", [components hour], [components minute]];
dateLabel = [NSString stringWithFormat:#"%lu/%lu/%lu", [components day], [components month], [components year]];
}
Exemple String: "05/01/2015 - 11:15"
Result: date: 1/1/2015, time: 11:15
and also how can I maintain this date format dd/mm/yyyy, I mean when the day is 1, it shows 01
Not tested but:
MM for the month. Not mm which is minutes.
You already have a NSDateFormatter so why not use it again instead of NSDateComponents and NSString formats?
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"MM/dd/yyyy '-' HH:mm"];
NSDate *date = [formatter dateFromString:dateString];
//Now you have the correct date. So we'll use the NSDateFormatter to transform NSDate (date) into NSString according to the format we need.
[formatter setDateFormat:#"MM/dd/yyyy"];
dateLabel = [formatter stringFromDate:date];
[formatter setDateFormat:#"HH:mm"];
hourLabel = [formatter stringFromDate:date];
hourLabel/dateLabel as NSString and not UILabel is quite a misleading var naming.
I am trying to display last 5 days date. But it display only last date(yesterday). I am using the following code to display it.
.h file:
NSInteger getDist;
NSString *lastdate;
NSDateFormatter *dateFormatter;
NSDate *sevenDaysAgo;
NSDate *dateAfterDecrement;
NSString *dateString;
int i;
viewDidLoad:
NSDate *currDate = [NSDate date];
dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd.MM.YY"];
dateString = [dateFormatter stringFromDate:currDate];
_currentDate.text=dateString;
-(void)display
{
for(i=1;i<=5;i++)
{
lastdate = _currentDate.text;
[dateFormatter setDateFormat:#"dd.MM.YY"];
sevenDaysAgo = [dateFormatter dateFromString:lastdate];
dateAfterDecrement=[sevenDaysAgo initWithTimeIntervalSinceNow:-
(24*60*60)];
}
_currentDate.text = [dateFormatter stringFromDate:dateAfterDecrement];
}
Please suggest me.
Here's how to display today's date, then the last 4 days' dates.
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM dd, yyyy"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
int DAY_TO_SECONDS = -60*60*24;
for (int n=0; n<5; n++)
{
NSDate* date = [[NSDate date] dateByAddingTimeInterval:DAY_TO_SECONDS*n];
NSString* dateString = [formatter stringFromDate:date];
NSLog(#"%#", dateString);
}
This produces output like:
2015-02-23 13:18:30.657 ClientInfo[1418:557691] Feb 23, 2015
2015-02-23 13:18:30.658 ClientInfo[1418:557691] Feb 22, 2015
2015-02-23 13:18:30.658 ClientInfo[1418:557691] Feb 21, 2015
2015-02-23 13:18:30.658 ClientInfo[1418:557691] Feb 20, 2015
2015-02-23 13:18:30.658 ClientInfo[1418:557691] Feb 19, 2015
you can decrement current date to this way by the number of days you want to get
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *datecomponents = [calendar components:NSYearCalendarUnit
| NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:[NSDate date]];
for (int i = 0; i < 5; ++i) {
NSDate *date = [calendar dateFromComponents:datecomponents];
NSLog(#"%#",date);
--datecomponents.day;
}
I'm using the code below to extract the date only from NSDate. What am I doing wrong?
NSDate* now = [NSDate date];
NSLog(#"Now Date %#",now);
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = #"dd-MM-yyyy";
NSString *stringDate = [format stringFromDate:now];
NSDate *todaysDate = [format dateFromString:stringDate];
NSLog(#"Today's Date without Time %#", todaysDate);
Log:
2014-06-21 12:27:23.284 App[69727:f03] Now Date 2014-06-21 19:27:23 +0000
2014-06-21 12:27:23.285 App[69727:f03] Today's Date without Time 2014-06-21 07:00:00 +0000
Why am I getting: 07:00:00 +0000 at the end?
I would like to get an NSDate in the in the following format:
2014-06-21 00:00:00 +0000
Having 0's for time, seconds, etc. is not important.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
should work
Another solution: using NSCalendar:
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:1]]; // I'm in Paris (+1)
NSDateComponents *comps = [cal components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:[NSDate date]];
comps.hour = 0;
comps.minute = 0;
comps.second = 0;
NSDate *newDate = [cal dateFromComponents:comps ];
NSLog(#"date: %#",newDate);
Adjust timezone param, you will receive something like: date: 2014-06-21 00:00:00 +0000
If you don't care about the time, NSDate is not the right storage structure for you. An NSDate represents a specific moment in time - there is no NSDate without a time. What you're seeing is the logged description of an NSDate, which is the full printout in GMT.
If you want to keep track of the year, month and day only, then use NSDateComponents instead, and extract only the components you are interested in. You can then use the components object and pass it around as you like.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSString *strDate = [dateFormatter stringFromDate:[NSDate date]];
With the code above, the NSDate object will HAVE time. But the string will be a date only text.
This is the code using .
#include <time.h>
- (NSDate *)dateFromISO8601String:(NSString *)string {
if (!string) {
return nil;
}
struct tm tm;
time_t t;
strptime([string cStringUsingEncoding:NSUTF8StringEncoding], "%Y-%m-%dT%H:%M:%S%z", &tm);
tm.tm_hour = 0;
tm.tm_min = 0;
tm.tm_sec = 0;
tm.tm_isdst = -1;
t = mktime(&tm);
return [NSDate dateWithTimeIntervalSince1970:t + [[NSTimeZone localTimeZone] secondsFromGMT]];
}
- (NSString *)ISO8601String:(NSDate*)aDate {
struct tm *timeinfo;
char buffer[80];
time_t rawtime = [aDate timeIntervalSince1970] - [[NSTimeZone localTimeZone] secondsFromGMT];
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%dT%H:%M:%S%z", timeinfo);
return [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
}
NSString *currentDateStr = [self ISO8601String:[NSDate date]];
NSDate *dateWithoutTime = [self dateFromISO8601String:currentDateStr];
NSLog(#"currentDateStr: %#",currentDateStr);
NSLog(#"dateWithoutTime: %#",dateWithoutTime);
I have 2 dates. Date1 in yyyy-MM-dd 21:00:00 +0000. Date2 in yyyy-MM-dd
I need to compare it and get age result.
Problem is that Ia have an error in NSDateComponents string.
NSDate *date1 = [NSDate date];
NSDate *date2temp = uBirthdate;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dateString = [dateFormatter stringFromDate:date2temp];
[dateString stringByAppendingString:#" 21:00:00 +0000"];
NSDate *date2 = [dateFormatter dateFromString:dateString];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:date2 toDate:date1 options:0];
NSInteger editedAge = components.year;
NSLog(#"%d ", editedAge);
It will be better to cut off '21:00:00 +0000' from date1, but I do not know how can I do it
In short words I plan to get current dateTime, change the time and make it local to Malaysia Time by applying +0800 to timezone.
The result is unexpected :
-(NSDate *)departureDateTime
{
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];
NSDate *newDate = [gregorian dateFromComponents: components];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-mm-dd HH:mm:ss Z"];
[dateFormat setLocale:[NSLocale currentLocale]];
NSString *newDateString = [NSString stringWithFormat:#"%#",newDate];
NSString *maskString = [NSString stringWithFormat:#"%#", [newDateString substringToIndex:20]];
NSString *append = [maskString stringByAppendingString:#"+0800"];
NSLog(#"%#",append);
NSDate *finalLocalDate = [dateFormat dateFromString:append];
return finalLocalDate;
}
Results :
for NSLog Append : 2013-12-07 23:59:17 +0800
but finalLocalDate : 2013-01-07 15:59:17 +0000
Found the answer with much shorter solution, so I posted here in case it helps anyone in future.
for returning, the problem was different time zones so by adding this line of
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ];
we set the timezone to system time zone then we remove unnecessary codes :
-(NSDate *)departureDateTime
{
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date];
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:(+0*3600) ] ];
[components setHour: 7];
[components setMinute: 59];
[components setSecond: 17];
NSDate *newDate = [gregorian dateFromComponents: components];
NSLog(#"%#",newDate);
return newDate;
}
Correct Result : 2013-12-08 07:59:17 +0000
try this:
NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
NSDate *malaysianTime = [NSDate dateWithTimeIntervalSince1970:now+(8*60*60)]; //8h in seconds
If your computer is running in the correct timezone don't set a timezone.
Create your newDate value and then --
NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:#"yyyy-MM-dd HH:mm:ss Z"];
NSString* printableDate = [fmt stringFromDate:newDate];
NSLog(#"The date is %#", printableDate);
Only set a timezone (in both NSCalendar and NSDateFormatter) if the desired timezone is not the one your computer/phone is currently using.
Note that if you NSLog newDate directly it will print in GMT timezone. This is the way it's supposed to be -- you always use NSDateFormatter for a printable date. When you NSLog an NSDate directly you get GMT, by design.