Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a system's date and timestamp

I have created a method to write a string of data to an text file. I was wondering how I could get the systems date and time and send it to the text file? Here is the method:

 -(void) writeToTextFile{

//get the documents dir
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/movbandlog.txt",
                      documentsDirectory];
//create content 
NSString *content = @"Data received from device\n \n \n \n \nData sent to Portal\n \n \n \n \nData received to Portal";

//save to documents directory
[content writeToFile:fileName
          atomically:NO
            encoding:NSStringEncodingConversionAllowLossy
               error:nil];

}
like image 723
TWcode Avatar asked Mar 15 '13 00:03

TWcode


People also ask

How do I get a timestamp from a date?

Getting the Current Time Stamp If you instead want to get the current time stamp, you can create a new Date object and use the getTime() method. const currentDate = new Date(); const timestamp = currentDate. getTime(); In JavaScript, a time stamp is the number of milliseconds that have passed since January 1, 1970.

How do I get a timestamp in R?

We can convert the character to timestamp by using strptime() method. strptime() function in R Language is used to parse the given representation of date and time with the given template.


1 Answers

Pure Cocoa

Use NSDate and optionally NSDateFormatter to format it:

NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd.MM.YY HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:currentDate];
// NSLog(@"%@",dateString);

// Adding your dateString to your content string
NSString *content = [NSString stringWithFormat:@"Data received from device\n \n \n \n \nData sent to Portal\n \n \n \n \nData received to Portal\n \n \n \n \nData received at %@", dateString];

Using Unix Functions

You might also consider using unix functions for unlocalized dates (timestamps)

struct tm  sometime;
const char *formatString = "%Y-%m-%d %H:%M:%S %z";
(void) strptime_l("2005-07-01 12:00:00 -0700", formatString, &sometime, NULL);
NSLog(@"NSDate is %@", [NSDate dateWithTimeIntervalSince1970: mktime(&sometime)]);
// Output: NSDate is 2005-07-01 12:00:00 -0700
like image 170
Michael Robinson Avatar answered Sep 30 '22 23:09

Michael Robinson