Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift - Convert a String to a Date and then to a String in a different format

Suppose I have a simple String, extracted from an array of strings (representing dates) -

var myDateString = "2015-11-25 04:31:32.0"

Now, I want to convert it to a string that looks like Nov 25, 2015.

For that, I assume I need to -

  • get a NSDate date object from string using NSDateFormatter
  • get a string from that NSDate object by using some functionality (which I've been unable to find)

I've been trying this in Playground, but have been unable to solve such a simple problem.

Here is what I have tried -

Line 1| var dateFormatter = NSDateFormatter()
Line 2| dateFormatter.locale = NSLocale.currentLocale()
Line 3| dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss.A"
Line 4| let somedate = dateFormatter.dateFromString(str)
Line 5| let somedateString = dateFormatter.stringFromDate(somedate!)

In the sidebar of Xcode, line 4 prints "Nov 25, 2015, 12:00 AM", but when I try to print a string from somedate, I get "2015-11-25 00:00:00.0".

I haven't found a single proper explanation of NSDates anywhere.

This was so much easier in Java with parse() and format() functions for Dates.

like image 909
Kunal Chawla Avatar asked Jan 16 '16 11:01

Kunal Chawla


People also ask

How do I convert a date to a String in Swift?

dateFormat = "yyyy-MM-dd'T'HH:mm:ss" dateFormatter. timeZone = NSTimeZone(name: "UTC") let date = dateFormatter. dateFromString("2015-04-01T11:42:00") // change to a readable time format and change to local time zone dateFormatter.

Can we convert String to date?

Let's see how to actually convert a String to a local date and time data type: Parse the API call: If the String value that we need to convert to the Date-time type is of ISO-801 format then we can simply call DateFormat and SimpleDateFormat classes using parse() methods.

How to convert a date to a string in Swift?

The DateFormatter class helps convert Date objects to their corresponding String representations and back. The code shows the 3 steps required to convert a Date to a String in Swift. // Convert string to Date let dateF = DateFormatter() // 1 dateF.dateStyle =.short // 2 dateF.string(from: today) // 3 // "8/23/20" Create a DateFormatter instance.

How to convert a string to a date in Java?

To convert the string to a date, we pass it to the date (from:) method of the DateFormatter class. Let's give that a try. import Foundation let string = "01/02/2016" let dateFormatter = DateFormatter() dateFormatter.date(from: string) The method seems to work fine since we don't see any errors or warnings.

How to convert string to date in SQL Server?

In SQL Server, converting string to date implicitly depends on the string date format and the default language settings (regional settings); If the date stored within a string is in ISO formats: yyyyMMdd or yyyy-MM-ddTHH:mm:ss (.mmm), it can be converted regardless of the regional settings, else the date must have a supported format ...

Why is it important to convert a string to a date?

Converting these values to a date data type is very important since dates may be more valuable during analysis. In SQL Server, converting a string to date can be achieved in different approaches.


2 Answers

Updated for Swift 3.0

You need two date formatters - one to make sense of your input string and convert to a NSDate, and a different formatter to create the output string

    let myDateString = "2016-01-01 04:31:32.0"

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.A"
    let myDate = dateFormatter.date(from: myDateString)!

    dateFormatter.dateFormat = "MMM dd, YYYY"
    let somedateString = dateFormatter.string(from: myDate)

I have updated this answer to change the date formatter from YYYY to yyyy. In most cases, there will be no difference between the two, but YYYY may treat the first few days of the year as being part of the last complete week of the previous year.

The Apple developer guides explain it like this.

A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

like image 145
Russell Avatar answered Sep 30 '22 06:09

Russell


You will need two date formatters as others suggested. Additionally, one of your issues is that you are using .A instead of .S for the fractional seconds. (See the link to Unicode Date Format Specification as pointed out in @MartinR's comment)

.A is Milliseconds in day

.S is Fractional Second

The the following in a Playground:

let dateString = "2015-11-25 04:01:32.0"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.S"                 // Note: S is fractional second
let dateFromString = dateFormatter.dateFromString(dateString)      // "Nov 25, 2015, 4:31 AM" as NSDate

let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "MMM d, yyyy"

let stringFromDate = dateFormatter2.stringFromDate(dateFromString!) // "Nov 25, 2015" as String
like image 28
So Over It Avatar answered Sep 30 '22 06:09

So Over It