Edem
Edem

Reputation: 53

How to set Date type variables to initial value?

I can't find the way to set Date type variables to initial or empty value(not use a user defined initial value...like '0001/01/01').

Like String type can set String.init() or "" to it's value, so can use isEmpty() to determine it is empty, but how to do that with Date type variables?

Upvotes: 3

Views: 2263

Answers (4)

Sulthan
Sulthan

Reputation: 130102

The obvious answer is that there is no empty Date.

A String has 3 possible states:

  1. there is some string, e.g. "abc"
  2. there is an empty string, that is, ""
  3. there is no string, that is, nil.

With strings, case 2 and 3 are usually interchangeable. That means that we can use either an empty string or nil to mean the same.

There are no empty Date values, therefore if we want to represent the state when there is no Date, we have to use nil.

var date: Date? = nil

Upvotes: 0

vadian
vadian

Reputation: 285082

It depends on what you are going to accomplish.

Naturally there is no empty date.

  • If the value of the date is irrelevant declare it with the current date

    let date = Date()
    
  • If the date is supposed to be quite unspecified in the distant past or future there are

    let date = Date.distantPast
    
    let date = Date.distantFuture
    
  • If the date can be a specific date use the reference dates

    let date = Date(timeIntervalSince1970: 0) // 1970/1/1
    
    let date = Date(timeIntervalSinceReferenceDate: 0) // 2001/1/1
    

Upvotes: 4

Kathiresan Murugan
Kathiresan Murugan

Reputation: 2962

You can declare a Date = nil Which means when we assign a value to data like

var date = Date() // means its current data

OR else

Use following codes to set a date from string format

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26") {
    print(dateFormatterPrint.string(from: date))
} else {
   print("There was an error decoding the string")
}

I hope this is helpful for you

Upvotes: 0

S1LENT WARRIOR
S1LENT WARRIOR

Reputation: 12214

You can initialize a Date object by its default constructor.

var date = Date()  

The above line will initialize the date object with the current date.
Hope this helps

Upvotes: 0

Related Questions