SwiftDate - string to date - ios

I use the SwiftDate library but I can't transform my string to date. This code return null
let date = "Tue, 19 Sep 2017 15:43:57 GMT".date(format: .custom("EEE, dd MMM yyyy HH:mm:ss zzz"))
Would anyone know why?

This code works now :
let region = Region(tz: TimeZoneName.gmt, cal: CalendarName.gregorian, loc: LocaleName.englishUnitedStates)
let date = "Tue, 19 Sep 2017 15:43:57 GMT".date(format: .custom("EEE, dd MMM yyyy HH:mm:ss zzz"), fromRegion: region)
Thank you for your help!

Related

In iOS Swift How can I convert the time from the format "Tue Aug 27 2019 07:01:59 GMT+0530 (India Standard Time)" to YYYY-MM-DD

From backend i am getting date as "Tue Aug 27 2019 07:01:59 GMT+0530 (India Standard Time)".
In iOS Swift, How can I convert the time from the format "Tue Aug 27 2019 07:01:59 GMT+0530 (India Standard Time)" to YYYY-MM-DD.
Removed 'GMT+0530 (India Standard Time)' from date string what are you getting from server
then use this -
let date = self.convertDateStringToFormatString1(dateString:
"Tue Aug 27 2019 07:01:59", fromFormat: "E MMM dd yyyy hh:mm:ss" , toFormat:
"YYYY-MM-dd")
func convertDateStringToFormatString1(dateString:String, fromFormat : String,
toFormat : String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = fromFormat
let date = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = toFormat
dateFormatter.locale = NSLocale.current
return dateFormatter.string(from: date!)
}

dateFromString returns nil for some values

I am getting nil for some values while using dateFromString in swift. I searched a lot but in vain.
Following is my code:
let strDate = self.sortedDict.valueForKey("TIME").objectAtIndex(indexPath.row).objectAtIndex(0) as? String
print(strDate);
let st_date = frmt.dateFromString(strDate!)
let frmt1:NSDateFormatter = NSDateFormatter()
frmt1.locale = NSLocale(localeIdentifier: localeStr)
frmt1.dateFormat = "MMM, dd yyyy hh:mm a"
if st_date != nil {
print(st_date)
}
Output console:
Optional("September, 20 2015 10:00:00")
Optional(2015-09-20 10:00:00 +0000)
Optional("October, 04 2015 10:00:00")
Optional(2015-10-04 10:00:00 +0000)
Optional("October, 04 2015 14:00:00") // nil
Optional("October, 18 2015 15:00:00") // nil
Optional("September, 20 2015 14:00:00") // nil
Optional("September, 27 2015 10:00:00")
Optional(2015-09-27 10:00:00 +0000)
Optional("September, 27 2015 12:00:00")
Optional(2015-09-27 00:00:00 +0000)
Optional("September, 27 2015 14:00:00")
Optional("October, 03 2015 14:00:00") //nil
Optional("October, 03 2015 16:00:00") //nil
The format is same for all date strings still I get nil for few values. Why so? Please help. Where am I getting wrong?
format should be HH for 24 hours even you are getting values only for 12 hours.
frmt1.dateFormat = "MMM, dd yyyy HH:mm a"

Get first day of week of year in Objective-C

I'm trying to find the first day of weeks using DateTools like so:
for (NSInteger week = 46; week <= 53; week++) {
NSDate *tempDate = [NSDate dateWithString:[NSString stringWithFormat:#"2015-%d", (int)week] formatString:#"Y-w"];
NSLog(#"INFO: tempDate: %#, day: %.2d, week: %d", tempDate, (int)[tempDate day], (int)week);
}
for (NSInteger week = 1; week <= 5; week++) {
NSDate *tempDate = [NSDate dateWithString:[NSString stringWithFormat:#"2016-%d", (int)week] formatString:#"Y-w"];
NSLog(#"INFO: tempDate: %#, day: %.2d, week: %d", tempDate, (int)[tempDate day], (int)week);
}
and I get this output:
INFO: tempDate: 2015-11-07 22:00:00 +0000, day: 08, week: 46
INFO: tempDate: 2015-11-14 22:00:00 +0000, day: 15, week: 47
INFO: tempDate: 2015-11-21 22:00:00 +0000, day: 22, week: 48
INFO: tempDate: 2015-11-28 22:00:00 +0000, day: 29, week: 49
INFO: tempDate: 2015-12-05 22:00:00 +0000, day: 06, week: 50
INFO: tempDate: 2015-12-12 22:00:00 +0000, day: 13, week: 51
INFO: tempDate: 2015-12-19 22:00:00 +0000, day: 20, week: 52
INFO: tempDate: 2015-12-26 22:00:00 +0000, day: 27, week: 53
INFO: tempDate: 2015-12-26 22:00:00 +0000, day: 27, week: 1
INFO: tempDate: 2016-01-02 22:00:00 +0000, day: 03, week: 2
INFO: tempDate: 2016-01-09 22:00:00 +0000, day: 10, week: 3
INFO: tempDate: 2016-01-16 22:00:00 +0000, day: 17, week: 4
INFO: tempDate: 2016-01-23 22:00:00 +0000, day: 24, week: 5
and as you can see, the week 53 from 2015 has the same day as the week 1 from 2016 (This site tells me that there are 53 weeks in 2015).
Actually, the week 1 from 2016 starts from 04.01.2016.
Also, notice the dateWithString:formatString: gives me the previous day of the first day of the week. Why is that? I can simply use dateByAddingDays:1 but I don't know if it's hackish and the problem should be solved somewhere else.
I tried using NSDateComponents as #DarkDust mentioned, to no avail. So this:
for (NSInteger week = 1; week <= 5; week++) {
NSDate *tempDate = [NSDate dateWithString:[NSString stringWithFormat:#"2016-%d", (int)week] formatString:#"Y-w"];
NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.year = 2016;
dateComponents.weekOfYear = week;
NSLog(#"INFO: tempDate: %#, day: %.2d, week: %d = %#", tempDate, (int)[tempDate day], (int)week, [calendar dateFromComponents:dateComponents]);
}
gives me this:
INFO: tempDate: 2015-12-26 22:00:00 +0000, day: 27, week: 1 = 2015-12-31 22:00:00 +0000
INFO: tempDate: 2016-01-02 22:00:00 +0000, day: 03, week: 2 = 2015-12-31 22:00:00 +0000
INFO: tempDate: 2016-01-09 22:00:00 +0000, day: 10, week: 3 = 2015-12-31 22:00:00 +0000
INFO: tempDate: 2016-01-16 22:00:00 +0000, day: 17, week: 4 = 2015-12-31 22:00:00 +0000
INFO: tempDate: 2016-01-23 22:00:00 +0000, day: 24, week: 5 = 2015-12-31 22:00:00 +0000
Here is the DateTools' dateWithString:formatString: implementation:
+ (NSDate *)dateWithString:(NSString *)dateString formatString:(NSString *)formatString {
return [self dateWithString:dateString formatString:formatString timeZone:[NSTimeZone systemTimeZone]];
}
+ (NSDate *)dateWithString:(NSString *)dateString formatString:(NSString *)formatString timeZone:(NSTimeZone *)timeZone {
static NSDateFormatter *parser = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
parser = [[NSDateFormatter alloc] init];
});
parser.dateStyle = NSDateFormatterNoStyle;
parser.timeStyle = NSDateFormatterNoStyle;
parser.timeZone = timeZone;
parser.dateFormat = formatString;
return [parser dateFromString:dateString];
}
As for the duplicate report:
The top 3 are wrong, 2 of them with downvotes, and they don't even do what I need at all.
This is a bad idea what you are doing. You must understand a date is a time stamp which can be interpreted differently depending on the time zone and the calendar you are using. As it was already mentioned in comments you should use date components for your solution. Note that printing out the date may use a different format and the result may not be expected.
Next a first weekday in a year depends on definition. If I remember correctly some standards (or all) will treat the first week of the year depending on what day of week is the first day. In other words if 1.1 is sunday then the first week of the year is in december but if it is tuesday then it is in january.
So if you want to find the beginning of the first monday of the given year the code should look something like this (I did not test it):
+ (NSDate *)firstWeekInYear:(NSInteger)year {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *toReturn = nil;
NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = year;
NSDate *beginningOfTheYear = [calendar dateFromComponents:components];
NSInteger day = [calendar component:NSCalendarUnitWeekday fromDate:beginningOfTheYear];
NSInteger daysToAdd = (8-day)%7;
toReturn = [calendar dateByAddingUnit:NSCalendarUnitDay value:daysToAdd toDate:beginningOfTheYear options:kNilOptions];
return toReturn;
}
So you need to choose the calendar, create date components with a target year, get the date from those components with the calendar to get the beginning of the year. Then find out what weekday that is and increase such a number of days so the result is the beginning of the first monday in a year.
I finally figured it out. #Matic's solution doesn't work in iOS 7 and it's hard to understand, so I managed to find a simpler solution that works on iOS 7 too:
+ (NSDate *)getFirstDayInWeek:(NSInteger)week ofYear:(NSInteger)year {
/* create the calendar only once */
static NSCalendar *calendar = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
calendar.firstWeekday = 2;
calendar.minimumDaysInFirstWeek = 4;
});
NSDateComponents *components = [NSDateComponents new]; // create an empty date components object
components.year = year;
components.weekOfYear = week; // set the number of the week in the year
components.weekday = calendar.firstWeekday; // important! set the result date's day of week
return [calendar dateFromComponents:components];
}

Can not format pubDate to NSDate iOS

I can not figure out why NSDate continues to throw nil.
NSString * copyString = [[self.parseResults objectAtIndex:indexPath.row]objectForKey:#"date"];
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:#"EEE, dd MMM yyyy HH:mm:ss zzz"];
NSDate *date = [df dateFromString:copyString];
NSLog(#"%#", copyString);
NSLog(#"%#",date);
Did I set the date format set properly?
Output from copyString
2014-01-24 11:17:25.893 Events[32755:70b] Wed, 31 Dec 1969 16:00:00
PST
2014-01-24 11:17:25.895 Events[32755:70b] Fri, 24 Jan 2014 20:00:00
PST
2014-01-24 11:17:25.896 Events[32755:70b] Sat, 25 Jan 2014 10:00:00
PST
2014-01-24 11:17:25.897 Events[32755:70b] Mon, 27 Jan 2014 10:00:00
PST
2014-01-24 11:17:25.899 Events[32755:70b] Mon, 27 Jan 2014 12:15:00
PST
2014-01-24 11:17:25.900 Events[32755:70b] Mon, 27 Jan 2014 19:00:00
PST
Output from date
2014-01-24 11:22:24.707 Events[32827:70b] (null)
2014-01-24 11:22:24.709 Events[32827:70b] (null)
2014-01-24 11:22:24.710 Events[32827:70b] (null)
2014-01-24 11:22:24.712 Events[32827:70b] (null)
2014-01-24 11:22:24.713 Events[32827:70b] (null)
2014-01-24 11:22:24.714 Events[32827:70b] (null)

Parsing NSString to NSDate using NSDateFormatter

I have such string: "Tue, 22 Oct 2013 1:59 pm EEST"
i am trying to set these parsing rules:
[formatter setDateFormat: #"EEE, dd MMM yyyy hh:mm a z"];
but this returns nil when i perform:
[formatter dateFromString: #"Tue, 22 Oct 2013 1:59 pm EEST"];
What's the right regular expression for such format?
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_GB"];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEE, dd MMM yyyy hh:mm a zzz"];
[formatter setLocale:locale];
NSDate* date = [formatter dateFromString:#"Tue, 22 Oct 2013 1:59 PM EEST"];
NSLog(#"date: %#",date);
O/P:-date: 2013-10-22 10:59:00 +0000
hh is a padded hour ("01" in your case) but your string doesn't have padded hours (just "1" ) so it should be just h instead.
You can see a practical examples of the different formatting components below (output from this GitHub gist). The date being formatted is 1987-08-27 15:24:03
format result
--------------
yy 87
yyyy 1987
M 8
MM 08
MMM Aug
MMMM August
dd 27
HH 15
hh 03 // <--.
h 3 // <--'--- note the difference
a PM
mm 24
m 24
ss 03
s 3

Resources