Convert date to timestamp in iOS - ios

How do you convert any given date to milliseconds? For example, 2014-01-23 to timestamp conversion.
NSDate *date = [dateFormatter dateFromString:#"2014-01-23"];
NSLog(#"date=%#",date);
NSTimeInterval interval = [date timeIntervalSince1970];
NSLog(#"interval=%f",interval);
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval];
[dateFormatter setDateFormat:#"yyyy/mm/dd "];
NSLog(#"result: %#", [dateFormatter stringFromDate:methodStart]);
Output result: 1970/30/01

Swift
Convert the current date/time to a timestamp:
// current date and time
let someDate = Date()
// time interval since 1970
let myTimeStamp = someDate.timeIntervalSince1970
See also
Convert Date to Integer in Swift
Creating a Date and Time in Swift
How to get the current time as datetime

Have it a try. "mm" stands for minute while "MM" stands for month.
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init] ;
[dateFormatter setDateFormat:#"yyyy-MM-dd"] ;
NSDate *date = [dateFormatter dateFromString:#"2014-01-23"] ;
NSLog(#"date=%#",date) ;
NSTimeInterval interval = [date timeIntervalSince1970] ;
NSLog(#"interval=%f",interval) ;
NSDate *methodStart = [NSDate dateWithTimeIntervalSince1970:interval] ;
[dateFormatter setDateFormat:#"yyyy/MM/dd "] ;
NSLog(#"result: %#", [dateFormatter stringFromDate:methodStart]) ;

NSTimeinterval is really a double, being seconds since a particular date (in your case, the start of 1970)

NOTE :- UNIX Timestamp format contains 13 Digits so we need a 1000 multiplication with the result.
And the timestamp must be UTC ZONE not our local Time Zone.
- (void)GetCurrentTimeStamp
{
NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
[objDateformat setDateFormat:#"yyyy-MM-dd"];
NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:#"2014-01-23"];
NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime];
long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
NSLog(#"Local Time = %#---- UTC = %# ----- TimeSatmp = %ld ---- TimeStamp = %lld",strTime,strUTCTime,unixTime,milliseconds);
}
- (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *objDate = [dateFormatter dateFromString:IN_strLocalTime];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
NSString *strDateTime = [dateFormatter stringFromDate:objDate];
return strDateTime;
}

[date1 timeIntervalSinceDate:date2] will return seconds from two NSDate objects.
double seconds = [date1 timeIntervalSinceDate:date2];
double milliSecondsPartOfCurrentSecond = seconds - [seconds intValue];
milliSecondsPartOfCurrentSecond

Related

How to remove the timezone offset from an NSDate

I am trying to get just yyyy-MM-dd HH:mm from an NSDateFormatter.
But the string spits out Historical Date: 2016-08-23 14:03:00 +0000
I do not want the seconds or the +0000.
What am I doing wrong?
int seconds = -( days * (24 * 60 * 60)); //24 hours, times 60 minutes, times 60 seconds
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString* stringFromDate = [format stringFromDate:[NSDate date]];
NSDate * pastDate = [[format dateFromString:stringFromDate] dateByAddingTimeInterval:seconds];
NSLog(#"Date: %#", pastDate);
It happens because you printing NSDate object.
NSDate object encapsulates a single point in time, it is not responsible for it's string representation.
What you really need to do, is to calculate exact date you need, and then format it into NSString.
Something like that:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm"];
NSDate *pastDate = [[NSDate date] dateByAddingTimeInterval:seconds];
NSString *yourDateInString = [dateFormatter stringFromDate:pastDate];
NSLog(#"%#", yourDateInString);
Also, it is good practice to use NSCalendar and NSCalendarComponents to manipulate with dates and calculate new dates instead of just adding time interval.
I tried your coding first
int seconds = -( 24 * (24 * 60 * 60)); //24 hours, times 60 minutes, times 60 seconds
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd HH:mm"];
NSString* stringFromDate = [format stringFromDate:[NSDate date]];
NSDate * pastDate = [[format dateFromString:stringFromDate] dateByAddingTimeInterval:seconds];
NSLog(#"The pastDate is - %#",pastDate);
The printed result is
The pastDate is - 2016-07-31 14:30:00 +0000
NSDate gets +0000
Then I tried with string
NSString *stringDate = [format stringFromDate:pastDate];
NSLog(#"The Date is: %#", stringDate);
Now the printed result is
The Date is: 2016-07-31 20:00
String does not have +0000

Convert epoch milliseconds to NSDate

I want to convert milliseconds elapsed since Jan 1 1970 to NSDate without loosing milliseconds. Every solution says to divide milliseconds by 1000 and use dateWithTimeIntervalSince1970. but I want to keep the preserve the to milliseconds as well.
The parameter to dateWithTimeIntervalSince1970 is a NSTimeInterval, which is not an integer value (it's a double). There's no reason to lose milliseconds. Just don't use integers when you perform your division.
For example:
long long milliseconds = 1576058147753;
NSTimeInterval seconds = (NSTimeInterval)milliseconds / 1000.0;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale localeWithLocaleIdentifier:#"en_US_POSIX"];
[formatter setLocalizedDateFormatFromTemplate:#"dMMMMyyyyHHmmssSSS"];
December 11, 2019, 01:55:47.753
Note the milliseconds of 753 are there.
You can get date in this way.You have to pass timeinterval and date format as per your requirement.
-(NSString *)getStringFromDate:(double)interval withFormat:(NSString*)format
{
if (interval == 0)
{
return #"";
}
double seconds = interval;
NSTimeInterval timeInterval = (NSTimeInterval)seconds;
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter* df_utc = [[NSDateFormatter alloc] init];
[df_utc setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
[df_utc setDateFormat:format];
NSString *Date=[df_utc stringFromDate:date];
return Date;
}
Hope this will help you.

NSDate To and From NSString

It is too much confusing and i have pasted my code below.
I have a eopoc time.
// Function that converts eopc to NSString
NSString * ConvertEpocToDateStr(NSString *epoc)
{
NSString *res;
NSTimeInterval sec = [epoc doubleValue]/1000.0;
NSDate *eDate = [[NSDate alloc] initWithTimeIntervalSince1970:sec];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd hh:mm a"];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"IST"];
NSLog (#" Time in your Zone is %# ", [[dateFormatter timeZone] description]);
res = [dateFormatter stringFromDate:eDate];
return res;
}
// From NSString to back NSDate.
NSDate * backToDate (NSString * dInStr )
{
NSDateFormatter *dFormatter = [[NSDateFormatter alloc] init];
[dFormatter setDateFormat:#"MM/dd hh:mm a"];
dFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"IST"];
NSDate *FromString = [dFormatter dateFromString:dInStr];
return dFromString;
}
And, I tried to print below .
epoc -> 1397600251077
ConvertEpocToDateStr -> 04/16 03:47 am
backToDate -> 2000-04-15 22:17:00 +0000
Both should be same right? I am not sure where/what i am missing?
Of course, you get the same dates. IST is 5.30 h ahead of GMT+0.
Since you drop out year in your direct formatter and use the date time string without the year
by default it is set to 2000.
Evidently, 2000-04-15 22:17:00 +0000 is the same as 2000-04-16 03:47:00 +0530.

NSDate: Extract Date ONLY

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);

JSON date string conversion issue in iOs

I am getting some UTC date strings from WCF Rest service and here is the format:
/Date(1354851639500+0530)/
I used the following code to convert the date:
//jsonDateString = 1354851639500+0530
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; //get number of seconds to add or subtract according to the client default time zone
NSTimeInterval unixTime = [[jsonDateString substringWithRange:NSMakeRange(0, 13)] doubleValue] / 1000; //WCF will send 13 digit-long value for the time interval since 1970 (millisecond precision) whereas iOS works with 10 digit-long values (second precision), hence the divide by 1000
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss a ZZZZ"];
NSString *stringFromDAte = [dateFormatter stringFromDate:[[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset]];
NSLog(#"Server GMT: %#", stringFromDAte);
NSDate *currentDadte = [dateFormatter dateFromString:stringFromDAte];
NSTimeInterval interval = [currentDadte timeIntervalSinceDate:[NSDate date]];
return [self dailyLanguage:interval];
But when I convert the time is not correct. I need to get the UTC time of the receiving time. But I am getting the time value without the offset value.
For example: if josnDate = 1354851639500+0530,
i am getting, 2012-12-07 03:40:39 AM GMT, but i should get 2012-12-07 09:10:39 (approx).
How can I do this? Please help.
Try this Code
- (NSDate *)deserializeJsonDateString: (NSString *)jsonDateString
{
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT]; //get number of seconds to add or subtract according to the client default time zone
NSInteger startPosition = [jsonDateString rangeOfString:#"("].location + 1; //start of the date value
NSTimeInterval unixTime = [[jsonDateString substringWithRange:NSMakeRange(startPosition, 13)] doubleValue] / 1000; //WCF will send 13 digit-long value for the time interval since 1970 (millisecond precision) whereas iOS works with 10 digit-long values (second precision), hence the divide by 1000
[[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset];
return date;
}
For more detail answer follow this link
http://goo.gl/lE6ut
You can try this
NSString *jsonDateString = [SingleResponseObject objectForKey:#"datetime"];;
NSInteger offset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval unixTime = [[jsonDateString substringWithRange:NSMakeRange(0, 13)] doubleValue] / 1000;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss a ZZZZ"];
NSString *stringFromDAte = [dateFormatter stringFromDate:[[NSDate dateWithTimeIntervalSince1970:unixTime] dateByAddingTimeInterval:offset]];
cell.date.text = stringFromDAte;

Resources