Format date from string

I am trying to format a date from a string to a different format.

For example: 2012-05-29 23:55:52 at 29/05 *newline* 2010 .

I just don't get logic for NSDate and NSDateFormatter, I think ..

Any help would be appreciated. Thanks:)

+4
source share
4 answers

You will need to create an NSDateFormatter and then set its dateFormat according to the first date, for example:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 

This will set the date format to find out your date string. Then you can get the NSDate object using

 NSDate *myDate = [dateFormatter dateFromString:myDateString]; // myDateString is the 2012-05-29 23:55:52 string 

This gives you the complete NSDate object representing this date. Now you need to reformat the date and return it back to the string, so set the date format in your formatter to a new format and get a new string representation of the returned date:

 [dateFormatter setDateFormat:@"dd/MM\nyyyy"]; NSString *newlyFormattedDateString = [dateFormatter stringFromDate:myDate]; [dateFormatter release], dateFormatter = nil; 

And voila! You have a new date :)

+9
source

If you only perform line processing of strings, then passing through the date object is not required.

  let dateString = "2012-05-29 23:55:52" let dateParts = dateString.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: "- :")) let newDateString = "\(dateParts[2])/\(dateParts[1])\n\(dateParts[0])" print(newDateString) 
+1
source

Please find the following code to convert dates from one format to another format. This will give time in your current zone.

 func convertDateFormat(sourceString : String, sourceFormat : String, destinationFormat : String) -> String{ let dateFormatter = DateFormatter(); dateFormatter.dateFormat = sourceFormat; if let date = dateFormatter.date(from: sourceString){ dateFormatter.dateFormat = destinationFormat; return dateFormatter.string(from: date) }else{ return "" } } 
0
source

For those who prefer to use the extension.

 extension String { func formattedDate(inputFormat: String, outputFormat: String) -> String { let inputFormatter = DateFormatter() inputFormatter.dateFormat = inputFormat if let date = inputFormatter.date(from: self) { let outputFormatter = DateFormatter() outputFormatter.dateFormat = outputFormat return outputFormatter.string(from: date) } else { return self // If the string is not in the correct format, we return it without formatting } } 

Using:

 tfDate.text = strDate.formattedDate(inputFormat: "yyyy-MM-dd", outputFormat: "dd/MM/yyyy") 
0
source

Source: https://habr.com/ru/post/1311353/


All Articles