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);
Related
I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.
I have my data in JSON format which contains some date:
"NOME_PUBBL_LINEA" = "FOLLONICA - PIOMBINO";
"ORA_ARRIVA" = "1899-12-30T06:45:00";
"ORA_PARTE" = "1899-12-30T05:50:00";
I want to convert it like :
ora_arriva = 6.45,
ora_parte = 5.50
I have tried following :
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd'T'HH:mm:ss'+02:00'"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"Italy/Rome"]];
NSDate *dte = [dateFormat dateFromString:dataDic[#"ORA_ARRIVA"]];
But it is giving me like
1899-12-30 00:51:40 +0000
for ora_arriva.
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'+02:00'"];
Just yyyy :)
dateFromString returns an NSDate. You need take that NSDate object and construct your time:
NSDate *myDate = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comp = [gregorianCalendar components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:myDate];
NSLog(#"current time = %ld:%ld", [comp hour], [comp minute]);
Replace the myDate with your actual NSDate you got back from your dateFormatter
You need something like this
[dateformatter setDateFormat:#"MM-dd-yyyy hh:mm:ss"];
NSString *dateString = [dateformatter stringFromDate:adate];
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.
I'm struggling to find a way to use NSDate for time only purposes.
I was trying to do the following code:
- (void)awakeFromInsert
{
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.minute = 45;
comps.second = 0;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
self.periodDuration = [calendar dateFromComponents:comps];
NSLog(#"periodDuration: %#",self.periodDuration);
comps = [[NSDateComponents alloc] init];
comps.hour = 8;
comps.minute = 0;
self.firstPeriodStartTime = [calendar dateFromComponents:comps];
NSLog(#"firstPeriodTime: %#",self.periodDuration);
}
But the result I get is:
periodDuration: 0001-12-31 22:24:04 +0000
firstPeriodTime: 0001-12-31 22:24:04 +0000
The result I was expecting:
periodDuration: 45:00
firstPeriodTime: 08:00
What am I doing wrong? How can I fix this?
Thank you.
The log of date is misleading you, if you are forming a date with only a few components you will not get a proper date instance which uniquely identifies a date and time.
If you try with this code snipped you can find that if you are just converting the dates back to string it is just as you expect
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.minute = 45;
comps.second = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *periodDate = [calendar dateFromComponents:comps];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss"];
NSLog(#"periodDuration: %#",[dateFormatter stringFromDate:periodDate]);
comps = [[NSDateComponents alloc] init];
comps.hour = 8;
comps.minute = 0;
NSDate *firstPeriodDate = [calendar dateFromComponents:comps];
[dateFormatter setDateFormat:#"HH:mm"];
NSLog(#"firstPeriodTime: %#",[dateFormatter stringFromDate:firstPeriodDate]);
periodDuration: 45:00
firstPeriodTime: 08:00
You can use NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
Use a NSTimeInterval (which is, basically, a double containing the number of seconds). To store it in CoreData:
[NSNumber numberWithDouble:myTimeInterval];
As for formatting: If you want more than 24h displayed, use this:
NSUInteger seconds = (NSUInteger)round(myTimeInterval);
NSString *formattedDate = [NSString stringWithFormat:#"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
NSLog(#"%#", formattedDate);
If you don't want more than 24h, you can use NSDate and NSDateFormatter again:
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:myTimeInterval];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(#"%#", formattedDate);
NSString *timeString;
timeString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterMediumStyle];
12:03:54 PM
I have a webservice that returns the date in this format:
2013-04-14
How do i figure out what day this corresponds to?
This code will take your string, convert it to an NSDate object and extract both the number of the day (14) and the name of the day (Sunday)
NSString *myDateString = #"2013-04-14";
// Convert the string to NSDate
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"yyyy-MM-dd";
NSDate *date = [dateFormatter dateFromString:myDateString];
// Extract the day number (14)
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:date];
NSInteger day = [components day];
// Extract the day name (Sunday)
dateFormatter.dateFormat = #"EEEE";
NSString *dayName = [dateFormatter stringFromDate:date];
// Print
NSLog(#"Day: %d: Name: %#", day, dayName);
Note: This code is for ARC. If MRC, add [dateFormatter release] at the end.
An alternate method for getting the weekday can be:
NSString *myDateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:myDateString];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date];
NSInteger weekday = [components weekday];
NSString *weekdayName = [dateFormatter weekdaySymbols][weekday - 1];
NSLog(#"%# is a %#", myDateString, weekdayName);
You can use this code it working for me.
NSString *dateString = #"2013-04-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter setDateFormat:#"EEEE"];
NSLog(#"%#", [dateFormatter stringFromDate:dateFromString]);
If you have 2013-04-14 stored in a NSString called date, then you can do this...
NSArray *dateComponents = [date componentsSeperatedByString:#"-"];
NSString *day = [dateComponents lastObject];
Swift 3:
let datFromat = DateFormatter()
datFormat.dateFormat = "EEEE"
let name = datFormat.string(from: Date())
Bonus: If you want to set your own date template instead of using Date() above:
let datFormat = DateFormatter()
datFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
let thisDate = datFormat.date(from: "2016-10-13T18:00:00-0400")
Then call the 1st code after this.