Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove time from a date like this 2016-02-10 00:00:00

hello I have a date like this

2016-02-10 00:00:00

I want to get only date from it in this style

14.05.2016 or 14-05-2016

This is what I have tried

let dateFormatter = NSDateFormatter()
let date = "2016-02-10 00:00:00"
dateFormatter.dateFormat = "dd-MM-yyyy"
let newdate = dateFormatter.dateFromString(date)
print(newdate) //nil is coming
like image 611
hellosheikh Avatar asked Feb 14 '16 13:02

hellosheikh


5 Answers

Using an extension on the Date:

extension Date {
    public var removeTimeStamp : Date? {
       guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: self)) else {
        return nil
       }
       return date
   }
}

Usage:

let now = Date()
let nowWithouTime = now.removeTimeStamp
like image 89
Umair Avatar answered Nov 13 '22 06:11

Umair


A better way than proposed versions is not to convert from date using a string formatter, but instead using calendar:

public func removeTimeStamp(fromDate: Date) -> Date {
    guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: fromDate)) else {
        fatalError("Failed to strip time from Date object")
    }
    return date
}
like image 45
Jeremie D Avatar answered Nov 13 '22 06:11

Jeremie D


okay I solved this myself

  let date = "2016-02-10 00:00:00"
  let dateFormatter = NSDateFormatter()

  dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
  let dateFromString : NSDate = dateFormatter.dateFromString(date)!
  dateFormatter.dateFormat = "dd-MM-yyyy"
  let datenew= dateFormatter.stringFromDate(dateFromString)

    print(datenew)
like image 36
hellosheikh Avatar answered Nov 13 '22 07:11

hellosheikh


Your code is not correct.

If you have NSDate instance that you want to convert to String using NSDateFormatter

You use this code:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let dateString = dateFormatter.stringFromDate(date)

The problem in your code is that you have a date string with value 2016-02-10 00:00:00 but you parse it using date format `dd-MM-yyyy' this is why you get a nil Date.

Instead you need to parse it first using dateFormatter.dateFormat = "yyy-MM-dd hh:mm:ss"

like image 2
Ahmad Baraka Avatar answered Nov 13 '22 07:11

Ahmad Baraka


Swift 5.5+

Use formatted(_:)

let now = Date.now
let date = now.formatted(.iso8601.year().month().day().dateSeparator(.dash))

Or formatted(date:time:)

let now = Date.now
let date = now.formatted(date: .abbreviated, time: .omitted)

Instead of .abbreviated, you may use a DateStyle such as .long, or .numeric.

https://developer.apple.com

like image 2
mahan Avatar answered Nov 13 '22 06:11

mahan