8

I can print the date in this format: Mon, Mar 19, 2018, but I am not sure how to get the Day of the week in this format.

Please help

Akshansh Thakur
  • 5,163
  • 2
  • 21
  • 38
S.S.D
  • 1,579
  • 2
  • 12
  • 23

6 Answers6

17
let dateFormatter = DateFormatter()
// uncomment to enforce the US locale
// dateFormatter.locale = Locale(identifier: "en-US") 
dateFormatter.setLocalizedDateFormatFromTemplate("EEE MMM d yyyy")
print(dateFormatter.string(from: Date())) // "Tue, Mar 20, 2018" for en-US locale

Note that I am using a template to provide the exact format, therefore the format will be properly localized in every language.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
12

To get the day for a particular date:

let customDateFormatter = DateFormatter()

print(customDateFormatter.weekdaySymbols[Calendar.current.component(.weekday, from: Date())])

// "Wednesday"

source

Akshansh Thakur
  • 5,163
  • 2
  • 21
  • 38
3

Rather than needing to spell out a date format. I would simplify it further to:

dateFormatter.dateStyle = .full

Or if you just want the day:

dateFormatter.dateFormat = "EEEE" 
dijipiji
  • 3,063
  • 1
  • 26
  • 21
2

With swift 4

 func timeStamp()->String {

      let dateFormater = DateFormatter()
      dateFormater.locale = Locale(identifier: "en-US") 
      dateFormater.setLocalizedDateFormatFromTemplate("EEE MMM d yyyy")

      return dateFormatter.string(from: Date())
    }

Use it.

let getTimeStamp = timeStamp()
   print(getTimeStamp)
MRizwan33
  • 2,723
  • 6
  • 31
  • 42
1

dateFormatter.dateFormat = "EEE, MMM dd, yyyy"

For dat of week in alphabets, you use EEEE or EEE similar to MMM & yyyy for month year.

Rishabh
  • 465
  • 5
  • 14
0

The best way to change your date is follow this method.

func ChangeDateFormat(date:String,FromFormat: String, ToFormat: String) -> String {
    let dateFormatter1 = DateFormatter()
    dateFormatter1.dateFormat = FromFormat
    let myDate = dateFormatter1.date(from: date)
    dateFormatter1.dateFormat = ToFormat
    if(myDate != nil){
        let Date = dateFormatter1.string(from: myDate!)
        return Date
    }
    else{
        return ""
    }
}

and then you can use this method like

String(ChangeDateFormat(date: StartDate, FromFormat: "yyyy-MM-dd hh:mm:ss a", ToFormat: "MMM d, yyyy"))

You can pass your date format in which format do you want in your case it should be

  String(ChangeDateFormat(date: StartDate, FromFormat: "Pass your date format", ToFormat: "EEE MMM d, yyyy"))
Raghav Chopra
  • 527
  • 1
  • 10
  • 26
  • 1
    please, learn to use `if let` or `guard let`. Also please use swift naming conventions, not conventions from other languages. – Sulthan Mar 20 '18 at 15:32