I'm getting time in HH:mm:ss format from web service and it is in Argentina(GMT-3) time zone. I want to convert this time into full date (dd-MM-yyyy HH:mm:ss) and finally convert it into device local time zone's date.
Here is my code
-(NSString *)getLocalTimeStringFrom:(NSString *)sourceTime
{
static NSDateFormatter* df = nil;
static NSDateFormatter* df1 = nil;
if (!df) {
df = [[NSDateFormatter alloc]init];
df.dateFormat = #"dd-MM-yyyy HH:mm:ss";
}
if (!df1) {
df1 = [[NSDateFormatter alloc]init];
df1.dateFormat = #"dd-MM-yyyy";
}
NSTimeZone *sourceZone = [NSTimeZone timeZoneWithAbbreviation:#"ART"];
[df setTimeZone: sourceZone];
[df1 setTimeZone: sourceZone];
NSString *artDate = [df1 stringFromDate:[NSDate date]]; // get 29-09-2015
NSString* timeStamp = [artDate stringByAppendingString:[NSString stringWithFormat:#" %#",sourceTime]]; // get 29-09-2015 00:05:00, if sourceTime is 00:05:00
NSDate *art = [df dateFromString:timeStamp];
NSLog(#"ART date %#" , art);//ART date 2015-09-29 03:05:00 +0000
NSTimeZone *localTimeZone = [NSTimeZone systemTimeZone];
[df setTimeZone: localTimeZone];
NSLog(#"Local date %#" , [df stringFromDate: art]);
return [df stringFromDate: ds];
}
The problem is that i'm getting UTC date in art (as commented in code),please note that the value of art is 2015-09-29 03:05:00 +0000 which is in UTC and format is yyyy-MM-dd HH:mm:ss, but is should be in ART and dd-MM-yyyy HH:mm:ss. I tried some code from net but didn't get solution. What is wrong in this code?
I use this:
NSDateFormatter* serverDf = [[NSDateFormatter alloc] init];
[serverDf setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-3*60*60]];
[serverDf setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate* gmtDate = [serverDf dateFromString:timeStamp];
// DDLogVerbose(#"DateTime in GMT: %#", gmtDate);
NSDateFormatter* localDF = [[NSDateFormatter alloc] init];
[localDF setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
[localDF setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
NSString *localDate = [localDF stringFromDate:gmtDate];
May you just want a formate NSString , but not a NSDate,
Because I think NSDate will add a '+0000'
Try this.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:yourString];
NSString *str = [dateFormatter stringFromDate:date];
Related
How to get the current time based on TimeZone in objective c?
example-> Current time for Asia/Kolkata.
Try this..
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"dd/MM/yyyy HH:mm"];
//Create the date assuming the given string is in GMT
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
//Create a date string in the local timezone
dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:[NSTimeZone localTimeZone].secondsFromGMT];
NSString *localDateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(#"date = %#", localDateString);
and if you want specific timezone date then see below code..
NSDate *myDate = [NSDate date];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateStyle:NSDateFormatterLongStyle];
[dateFormatter1 setTimeStyle:NSDateFormatterLongStyle];
[dateFormatter1 setDateFormat:#"dd/MM/yyy hh:mm a"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName: #"Asia/Calcutta"];
[dateFormatter1 setTimeZone:timeZone];
NSString *dateString = [dateFormatter1 stringFromDate: myDate];
NSLog(#"%#", dateString);
I want to log the server time in my iOS app , I am using NHNetworkTime library to get the network time, when I try to print the following code its showing GMT, through I have chosen UTC, how to print the date time in UTC?
NSDate* datetime = [NSDate networkDate];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]]; // Prevent adjustment to user's local time zone.
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss.SSS Z z "];
NSString* dateTimeInIsoFormatForZuluTimeZone = [dateFormatter stringFromDate:datetime];
NSLog(#"%#",dateTimeInIsoFormatForZuluTimeZone);
this is printing 2016-03-09 06:51:23.406 +0000 GMT
There is no time difference between Coordinated Universal Time (UTC) and Greenwich Mean Time(GMT). you can get more info from here More info
Refer :-
-(NSString *)getUTCFormateDate:(NSDate *)localDate
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:localDate];
[dateFormatter release];
return dateString;
}
Moreover to get time
-(NSString *)getTimeFromDate:(NSDate *)localDate
{
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc]init]autorelease];
dateFormatter.dateFormat = #"MM/dd/yy";
NSString *dateString = [dateFormatter stringFromDate: localDate];
NSDateFormatter *timeFormatter = [[[NSDateFormatter alloc]init]autorelease];
timeFormatter.dateFormat = #"HH:mm:ss";
return [timeFormatter stringFromDate: localDate];
}
Hi I am parsing an end point of API, from there I am getting a string which contain like this date string 2016-01-18T13:28:06.357 but I want to convert this like 01 Jan 16, I have tried many times by using different format one of following mentioned. kindly need suggestion how to accomplish this task.
NSString * date = [dictionary objectForKey:#"date"];
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setTimeZone:[NSTimeZone timeZoneWithName:#"EST"]];
[dateformat setDateFormat:#"dd MMM yyyy"];
NSDate *myDate = [dateformat date];
// Objective C
NSString * date = [dictionary objectForKey:#"date"];
NSDateFormatter *dateformat = [[NSDateFormatter alloc] init];
[dateformat setTimeZone:[NSTimeZone timeZoneWithName:#"EST"]];
[dateformat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS"];
NSDate *myDate = [dateformat dateFromString:date];
[dateformat setDateFormat:#"dd MMM yyyy"];
NSString *strDate=[dateformat stringFromDate:myDate];
// Swift 3.0
var date = (dictionary["date"] as! String)
var dateformat = DateFormatter()
dateformat.timeZone = NSTimeZone(name: "EST")
dateformat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
var myDate = dateformat.date(fromString: date)!
dateformat.dateFormat = "dd MMM yyyy"
var strDate = dateformat.string(from: myDate)
You should use this format:
NSString *dateStr = #"2016-01-18T13:28:06.357";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS"];
NSDate *date = [formatter dateFromString:dateStr];
// date is 2016-01-18 08:28:06 +0000
And next convert that date to format you need
You can also use this :
NSString *dateString = #"2016-01-18T13:28:06.357";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *date = [dateFormatter dateFromString:dateString];
// Convert date object into desired format
[dateFormatter setDateFormat:#"dd MMMM yy"];
NSString *newDateString = [dateFormatter stringFromDate:date];
NSLog(#"newDateString=%#",newDateString);
You should use this format code
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//Get Date
[formatter setDateFormat:#"dd"];
NSString *strDate = [formatter stringFromDate:[NSDate date]];
NSLog(#"Date is - %#",strDate);
//Get Month
[formatter setDateFormat:#"MMM"];
NSString *strMonth = [formatter stringFromDate:[NSDate date]];
NSLog(#"Month is - %#",strMonth);
//Get Year
[formatter setDateFormat:#"yyyy"];
NSString *strYear = [formatter stringFromDate:[NSDate date]];
NSLog(#"Year is - %#",strYear);
Log is :
Date is - 05
Month is - Feb
Year is - 2016
for set more format, Click Me
I am trying to get date in the format Monday, March 09, 2015. But following code is not returning required date format. I think I am using wrong Formatter. Here is the code:
NSString *dateString = #"09-03-2015";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd MMMM yyyy"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
NSLog(#"%#",[dateFormatter stringFromDate:date]);
try this...
//Getting date from string
NSString *dateString = #"09-03-2015";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
// converting into our required date format
[dateFormatter setDateFormat:#"EEEE, MMMM dd, yyyy"];
NSString *reqDateString = [dateFormatter stringFromDate:date];
NSLog(#"date is %#", reqDateString);
LOG:2015-03-09 12:40:33.456 TestCode [1377:38775] date is Monday, March 09, 2015
Firstly you must convert your dateString to NSDatevalue
NSString *dateString = #"09-03-2015";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
NSLog(#"%#",[dateFormatter stringFromDate:date]);
after that you could use this format: #"EEEE,MMMM dd, yyyy" to convert that dateValue to dateString like Monday, March 09, 2015
Hope this help
Helpful link for you
Try to set dateFormat property to #"dd'-'MM'-'yyyy" . Always check the unicode the date symbol table. "MMMM" means that the date month should be a full month name.
Try this one..
NSString * yourJSONString = #"09-03-2015";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];;
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *dateFromString = [dateFormatter dateFromString:yourJSONString];
[dateFormatter setDateFormat:#"EEEE,LLLL dd, yyyy"];
NSString *output = [dateFormatter stringFromDate:dateFromString];
NSLog(#"%#", output);
Try this:-
NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSString * format = [NSDateFormatter dateFormatFromTemplate:#"EEEEMMMMdyyyy" options:0 locale:[NSLocale currentLocale]];
[formatter setDateFormat:format];
NSString *dateFormatted = [fullDateFormatterTime stringFromDate: date];
NSLog(#"Formatted date: %#", dateFormatted);
How do I convert a UTC NSDate to local timezone NSDate in Objective C or/and Swift?
NSTimeInterval seconds; // assume this exists
NSDate* ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds];
NSDateFormatter* df_utc = [[[NSDateFormatter alloc] init] autorelease];
[df_utc setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[df_utc setDateFormat:#"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease];
[df_local setTimeZone:[NSTimeZone timeZoneWithName:#"EST"]];
[df_local setDateFormat:#"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
NSString* ts_utc_string = [df_utc stringFromDate:ts_utc];
NSString* ts_local_string = [df_local stringFromDate:ts_utc];
// you can also use NSDateFormatter dateFromString to go the opposite way
Table of formatting string parameters:
https://waracle.com/iphone-nsdateformatter-date-formatting-table/
If performance is a priority, you may want to consider using strftime
https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/strftime.3.html
EDIT When i wrote this I didn't know I should use a dateformatter which is probably a better approach, so check out slf's answer too.
I have a webservice that returns dates in UTC. I use toLocalTime to convert it to local time and toGlobalTime to convert back if needed.
This is where I got my answer from:
https://agilewarrior.wordpress.com/2012/06/27/how-to-convert-nsdate-to-different-time-zones/
#implementation NSDate(Utils)
-(NSDate *) toLocalTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = [tz secondsFromGMTForDate: self];
return [NSDate dateWithTimeInterval: seconds sinceDate: self];
}
-(NSDate *) toGlobalTime
{
NSTimeZone *tz = [NSTimeZone defaultTimeZone];
NSInteger seconds = -[tz secondsFromGMTForDate: self];
return [NSDate dateWithTimeInterval: seconds sinceDate: self];
}
#end
The easiest method I've found is this:
NSDate *someDateInUTC = …;
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [someDateInUTC dateByAddingTimeInterval:timeZoneSeconds];
Swift 3+: UTC to Local and Local to UTC
extension Date {
// Convert UTC (or GMT) to local time
func toLocalTime() -> Date {
let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
// Convert local time to UTC (or GMT)
func toGlobalTime() -> Date {
let timezone = TimeZone.current
let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
return Date(timeInterval: seconds, since: self)
}
}
If you want local Date and time. Try this code:-
NSString *localDate = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterMediumStyle];
Convert your UTC date to Local Date
-(NSString *)getLocalDateTimeFromUTC:(NSString *)strDate
{
NSDateFormatter *dtFormat = [[NSDateFormatter alloc] init];
[dtFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[dtFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSDate *aDate = [dtFormat dateFromString:strDate];
[dtFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[dtFormat setTimeZone:[NSTimeZone systemTimeZone]];
return [dtFormat stringFromDate:aDate];
}
Use Like This
NSString *localDate = [self getLocalDateTimeFromUTC:#"yourUTCDate"];
Here input is a string currentUTCTime (in format 08/30/2012 11:11) converts input time in GMT to system set zone time
//UTC time
NSDateFormatter *utcDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[utcDateFormatter setDateFormat:#"MM/dd/yyyy HH:mm"];
[utcDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: 0]];
// utc format
NSDate *dateInUTC = [utcDateFormatter dateFromString: currentUTCTime];
// offset second
NSInteger seconds = [[NSTimeZone systemTimeZone] secondsFromGMT];
// format it and send
NSDateFormatter *localDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[localDateFormatter setDateFormat:#"MM/dd/yyyy HH:mm"];
[localDateFormatter setTimeZone :[NSTimeZone timeZoneForSecondsFromGMT: seconds]];
// formatted string
NSString *localDate = [localDateFormatter stringFromDate: dateInUTC];
return localDate;
//This is basic way to get time of any GMT time.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"hh:mm a"]; // 09:30 AM
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:1]]; // For GMT+1
NSString *time = [formatter stringFromDate:[NSDate date]]; // Current time
Convert the date from the UTC calendar to one with the appropriate local NSTimeZone.
I write this Method to convert date time to our LocalTimeZone
-Here (NSString *)TimeZone parameter is a server timezone
-(NSString *)convertTimeIntoLocal:(NSString *)defaultTime :(NSString *)TimeZone
{
NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init];
[serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:TimeZone]];
[serverFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *theDate = [serverFormatter dateFromString:defaultTime];
NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
[userFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[userFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *dateConverted = [userFormatter stringFromDate:theDate];
return dateConverted;
}
Since no one seemed to be using NSDateComponents, I thought I would pitch one in...
In this version, no NSDateFormatter is used, hence no string parsing, and NSDate is not used to represent time outside of GMT (UTC). The original NSDate is in the variable i_date.
NSCalendar *anotherCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:i_anotherCalendar];
anotherCalendar.timeZone = [NSTimeZone timeZoneWithName:i_anotherTimeZone];
NSDateComponents *anotherComponents = [anotherCalendar components:(NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitNanosecond) fromDate:i_date];
// The following is just for checking
anotherComponents.calendar = anotherCalendar; // anotherComponents.date is nil without this
NSDate *anotherDate = anotherComponents.date;
i_anotherCalendar could be NSCalendarIdentifierGregorian or any other calendar.
The NSString allowed for i_anotherTimeZone can be acquired with [NSTimeZone knownTimeZoneNames], but anotherCalendar.timeZone could be [NSTimeZone defaultTimeZone] or [NSTimeZone localTimeZone] or [NSTimeZone systemTimeZone] altogether.
It is actually anotherComponents holding the time in the new time zone. You'll notice anotherDate is equal to i_date, because it holds time in GMT (UTC).
You can try this one:
NSDate *currentDate = [[NSDate alloc] init];
NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"ZZZ"];
NSString *localDateString = [dateFormatter stringFromDate:currentDate];
NSMutableString *mu = [NSMutableString stringWithString:localDateString];
[mu insertString:#":" atIndex:3];
NSString *strTimeZone = [NSString stringWithFormat:#"(GMT%#)%#",mu,timeZone.name];
NSLog(#"%#",strTimeZone);
Please use this code.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSDate *date = [dateFormatter dateFromString:#"2015-04-01T11:42:00"]; // create date from string
[dateFormatter setDateFormat:#"EEE, MMM d, yyyy - h:mm a"];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSString *timestamp = [dateFormatter stringFromDate:date];
Solution for SwiftDate library:
// Take date by seconds in UTC time zone
var viewModelDate: Date = DateInRegion(seconds: Double(backendModel.scheduledTimestamp)).date
...
// Convert date to local timezone and convert to string by format rule.
label.text = viewModelDate.convertTo(region: .current).toFormat(" EEE MM/dd j:mm")
Convert UTC time to current time zone.
call function
NSLocale *locale = [NSLocale autoupdatingCurrentLocale];
NSString *myLanguageCode = [locale objectForKey: NSLocaleLanguageCode];
NSString *myCountryCode = [locale objectForKey: NSLocaleCountryCode];
NSString *rfc3339DateTimeString = #"2015-02-15 00:00:00"];
NSDate *myDateTime = (NSDate*)[_myCommonFunctions _ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeString LanguageCode:myLanguageCode CountryCode:myCountryCode Formated:NO];
Function
-NSObject*)_ConvertUTCTimeToLocalTimeWithFormat:rfc3339DateTimeString LanguageCode:(NSString *)lgc CountryCode:(NSString *)ctc Formated:(BOOL) formated
{
NSDateFormatter *sUserVisibleDateFormatter = nil;
NSDateFormatter *sRFC3339DateFormatter = nil;
NSTimeZone *timeZone = [NSTimeZone defaultTimeZone];
if (sRFC3339DateFormatter == nil)
{
sRFC3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *myPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:[NSString stringWithFormat:#"%#", timeZone]];
[sRFC3339DateFormatter setLocale:myPOSIXLocale];
[sRFC3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
}
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [sRFC3339DateFormatter dateFromString:rfc3339DateTimeString];
if (formated == YES)
{
NSString *userVisibleDateTimeString;
if (date != nil)
{
if (sUserVisibleDateFormatter == nil)
{
sUserVisibleDateFormatter = [[NSDateFormatter alloc] init];
[sUserVisibleDateFormatter setDateStyle:NSDateFormatterMediumStyle];
[sUserVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];
}
// Convert the date object to a user-visible date string.
userVisibleDateTimeString = [sUserVisibleDateFormatter stringFromDate:date];
return (NSObject*)userVisibleDateTimeString;
}
}
return (NSObject*)date;
}