i have a module in that i have 7 buttons all the 7 buttons indicates date for action, i.e first button has current date, second button has tomorrow date, third button has day after tomorrow date likes go on till 7th button, i implemented code from one post to get info like that, but my problem is i can't convert date into string, i need to remove and replace the output value and send it to server
here my sample code :
func addDaystoGivenDate(baseDate:NSDate,NumberOfDaysToAdd:Int)->NSDate
{
let dateComponents = NSDateComponents()
let CurrentCalendar = NSCalendar.currentCalendar()
let CalendarOption = NSCalendarOptions()
dateComponents.day = NumberOfDaysToAdd
let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: baseDate, options: CalendarOption)
return newDate!
}
override func viewDidLoad() {
let newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 1)
print(newDate)
}
my output is : 2016-04-06 08:35:59 +0000
but my expected output is : 06/04
can anyone solve my issues
You should be able to format your date right with this:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM"
let dateStr = dateFormatter.stringFromDate(newDate!)
// dateStr now contains the string "06/04"
Swift 3.0:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM"
let dateStr = dateFormatter.string(from: newDate)
Related
How can I get local date and time in Swift?
let last_login = String(NSDate.date())
update: Xcode 8.2.1 • Swift 3.0.2
You can also use the Date method description(with locale: Locale?) to get user's localized time description:
A string representation of the Date, using the given locale, or if the locale
argument is nil, in the international format YYYY-MM-DD HH:MM:SS
±HHMM, where ±HHMM represents the time zone offset in hours and
minutes from UTC (for example, “2001-03-24 10:45:32 +0600”).
description(with locale: Locale?)
Date().description(with: .current) // "Monday, February 9, 2015 at 05:47:51 Brasilia Summer Time"
The method above it is not meant to use when displaying date and time to the user. It is for debugging purposes only.
When displaying local date and time (current timezone) to the user you should respect the users locale and device settings. The only thing you can control is the date and time style (short, medium, long or full). Fore more info on that you can check this post shortDateTime.
If your intent is to create a time stamp UTC for encoding purposes (iso8601) you can check this post iso8601
In case you want to get a Date object and not a string representation you can use the following snippet:
extension Date {
func localDate() -> Date {
let nowUTC = Date()
let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: nowUTC))
guard let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) else {return Date()}
return localDate
}
}
Use it like this:
let now = Date().localDate()
Leo's answer great. I just wanted to add a way to use it as a computed property.
var currentTime: String {
Date().description(with: .current)
}
Use it like so:
print(currentTime)
Or you can encapsulate it:
extension String {
static var currentTime: String {
Date().description(with: .current)
}
}
And then you can use it anywhere you use a string:
var time: String = .currentTime
use NSDateFormatter, either by setting the format
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm"
println(dateFormatter.stringFromDate(NSDate()))
or styles
dateFormatter.dateStyle = .NoStyle
dateFormatter.timeStyle = .MediumStyle
I already found the answer.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
let dateInFormat = dateFormatter.stringFromDate(NSDate())
let expiryDate: Date = ...
let localizedDateString = DateFormatter.localizedString(from: expiryDate, dateStyle: .medium, timeStyle: .short)
"10 Sep 2017, 14:37"
To get back the most common string formats (when dealing with queries and databases):
Swift 4, 5
2019-01-09T01:07:04Z (RFC3339 in GMT/Zulu time)
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
let s = f.string(from: Date())
2019-01-08T17:04:16-08:00 (RFC3339 accounting for local time zone)
let f = ISO8601DateFormatter()
f.formatOptions = [.withInternetDateTime]
f.timeZone = TimeZone.current
let s = f.string(from: Date())
2019-01-09 (standard date stamp in GMT/Zulu time)
let f = ISO8601DateFormatter()
f.formatOptions = [.withFullDate, .withDashSeparatorInDate]
let s = f.string(from: Date())
2019-01-08 (standard date stamp accounting for local time zone)
let f = ISO8601DateFormatter()
f.formatOptions = [.withFullDate, .withDashSeparatorInDate]
f.timeZone = TimeZone.current
let s = f.string(from: Date())
All four strings represent the exact same point in time. And remember that sorting these strings in alphabetical order also sorts them into chronological order, which makes this data database agnostic (which I always aim for).
You have to use NSDateFormatter
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMMM dd, yyyy HH:mm"
dateFormatter.locale = "en" // Change "en" to change the default locale if you want
let stringDate = dateFormatter.stringFromDate(date)
Refactor the answer with swift 5 base on #lajosdeme. My location is in China.
import Foundation
let date = Date() // It is not the local time, less than 8 hours
print(date) // 2022-08-05 08:04:20 +0000
extension Date {
static func localDate() -> Date {
let nowUTC = Date()
let timeZoneOffset = Double(TimeZone.current.secondsFromGMT(for: nowUTC))
guard let localDate = Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC) else {
return nowUTC
}
return localDate
}
}
// It is the local time
print(Date.localDate()) // 2022-08-05 16:04:20 +0000
Swift 4
To get current date and time
let currentDate = Date()
print(currentDate) //this will return current date and time
but that will be in date type to convert date into string
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm" //give the formate according to your need
let dateStr = dateFormatter.string(from: currentDate) //which will give the string of current date and time in required dateformate
My understanding of Swift Date is that Date is a time point without any calendar or timezone information. I think it is GMT time. If you want to show a date in a specified timezone, you have to use DateFormat API to format the date to a string.
I have an iOS app TapToCount-3W to make notes with date and GPS location information. When I travel, I use it to record/tap a note with date and GPS. The dates are local date when I am in travel countries. However, the problem I found is that when I come back home, the travel dates displayed are in my home country dates instead of those travel country timezones.
I am working on updates with my app now. The solution is to add timezone information when a tap is made. With date and timezone information, the localized dates will be correctly displayed.
The method as recommended in this QA to extend Date is actually to create date from Date() from second offset from GMT time. It is a GMT time and different date from Date().
The following codes are from my updates(I also included #lajosdeme method as comparison):
extension Date {
private func getLocalByID(_ identifier: String?) -> Locale
{
let local: Locale
if let id = identifier, !id.isEmpty {
local = Locale(identifier: id)
} else {
local = Locale.current
}
return local
}
func localizedString(
timezone: String?,
dateStyle: DateFormatter.Style = .short,
timeStyle: DateFormatter.Style = .long
) -> String
{
let dtFormater = DateFormatter()
let tz: String = timezone ?? ""
dtFormater.locale = getLocalByID(tz)
dtFormater.dateStyle = dateStyle
dtFormater.timeStyle = timeStyle
if let timeZone = TimeZone(identifier: tz) {
dtFormater.timeZone = timeZone
}
return dtFormater.string(from: self)
}
func dateForTimezone(_ timezone: String?) -> Date {
let nowUTC = Date()
let tz: TimeZone
if let timezone = timezone,
let v = TimeZone(identifier: timezone)
{
tz = v
} else {
tz = TimeZone.current
}
let timeZoneOffset =
Double(tz.secondsFromGMT(for: nowUTC))
if let dt =
Calendar.current.date(byAdding: .second, value: Int(timeZoneOffset), to: nowUTC)
{
return dt
}
else {
return Date()
}
}
}
// Test above extension in Playground
// [SwiftFiddle][3]
let dt1 = Date()
let tz = "America/Edmonton"
let dt2 = dt1.description(with: .current)
let dt3 = dt1.localizedString(timezone: tz)
let dt4 = dt1.dateForTimezone(tz)
print("Timezone: \(tz)\nDate: \(dt1)\ndescription: \(dt2)\nlocalized string: \(dt3)\ndateForTimezone: \(dt4)")
Here are the test result from SwiftFiddle playground:
Timezone: America/Edmonton
Date: 2022-06-03 15:41:23 +0000
description: Friday, June 3, 2022 at 3:41:23 PM Coordinated Universal Time
localized string: 6/3/22, 9:41:23 AM GMT-6
dateForTimezone: 2022-06-03 09:41:23 +0000
I am new in this forum but it helped me a lot in coding.
Currently I am trying to code an iOS App as a time calculator in Swift (Xcode 11.2.1)
It should be able to pick a time from the DatePicker component and add 8 hours worktime to it.
So the function is to display the time you can leave your workplace without getting negative in your flextime.
It should be displayed in the Label component.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var dateLabel: UILabel!
#IBOutlet weak var datePicker: UIDatePicker!
#IBAction func datePickerChanged(_ sender: Any) {
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.short //show time in h:mm format
dateFormatter.locale = Locale(identifier: "de-DE") //locale Germany
let endTime = dateFormatter.date // declaring as date
let calendar = Calendar.date(from: endTime) // get time from UIDatePicker
let addHours = Calendar.date(byAdding: .hour, value: 8, to: endTime) // add 8 hours
let endTimeString = dateFormatter.string(from: endTime) //convert time from date to String
dateLabel.text = endTimeString // show calculated time in UILabel
}
}
I am getting 3 errors.
In the first let calendar line it says:
Instance member 'date' cannot be used on type 'Calendar'; did you mean to use a value of this type instead?
In the following let addHours line I am getting the same error again, what is the point here?
The last error starts at the line when I am trying to convert the time from type date to String.
Cannot convert value of type '(String) -> Date?' to expected argument type 'Date'
Anyone could help me?
I think you want something like this:
#IBAction func datePickerChanged(_ sender: UIDatePicker) {
var pickerDate = sender.date
let calendar = Calendar.current
guard let endDate = calendar.date(byAdding: .hour, value: 8, to: pickerDate) else { return }
let dateFormatter = DateFormatter()
dateFormatter.timeStyle = DateFormatter.Style.short //show time in h:mm format
dateFormatter.locale = Locale(identifier: "de-DE") //locale Germany
var endTimeString = dateFormatter.string(from: endDate) //convert time from date to String
dateLabel.text = endTimeString // show calculated time in UILabel
}
First, you need to get the selected date from the UIDatePicker.
Then, for date calulations, you need to specify a calendar to work with. Typically the current calendar is what you want (this is the calendar specified for the device). Then, add 8 hours and convert it to a string.
Btw.: you need to keep in mind that when the user picks a date in the evening, there is a "day flip" when you add 8 hours.
Update
To add somthing like 8 hours and 13 minutes, it's best to use DateComponents:
var now = Date()
var calendar = Calendar.current
var addComp = DateComponents(calendar:calendar,
hour:8,
minute:13)
if let then = calendar.date(byAdding: addComp, to: now, wrappingComponents:false) {
print(now)
print(then!)
}
Basically my challenge is :
I got an array of objects . Each object has a date property .
I want to get the array of objects which matches today's date.
So, I want to group the array based on date.
I want to show in history list by grouping objects from today, yesterday, last 7 days ,.....
I can sort array using sort function:
historylist.sort(by: {$0.createdDate! as Date > $1.createdDate! as Date })
But I need a filter function based on date.
I want all the data in historicist which are created today only.
Any quick pseudo code .
Thanks.
let date1 = NSDate()
let date2 = NSDate()
let dates = [date1, date2]
let calendar = NSCalendar.currentCalendar()
let todayDates = dates.filter({calendar.isDateInToday($0)})
Demo of how this works with filtering date objects:
let d1 = Date().addingTimeInterval(22000000)
let d2 = Date().addingTimeInterval(23000000)
let d3 = Date().addingTimeInterval(30000000)
let dates = [d1, d2, d3, Date(), Date()]
let calendar = Calendar.current
let todayDates = dates.filter({calendar.isDateInToday($0 as Date)})
print(todayDates) // [2017-06-03 15:50:11 +0000, 2017-06-03 15:50:11 +0000]
So in your case you should do it like this:
let todayDates = historylist.filter({calendar.isDateInToday($0.createdDate as Date)})
Update:
To convert a string to a Date use the following:
extension String {
var toDate: Date {
return Date.Formatter.customDate.date(from: self)!
}
}
extension Date {
struct Formatter {
static let customDate: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MM-dd-yyyy hh:mm:ss a"
return formatter
}()
}
}
let strDate = "06-01-2017 09:32:48 PM"
let date = strDate.toDate
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
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
}
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
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)
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"
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
If you have an input date string (or rather, date-and-time string) in one format and you want to output in a different format then you need 2 date formatters: An input formatter that takes the source string format and converts it to an NSDate (using dateFromString) and then an output formatter that takes the NSDate and converts it to your output date string (using stringFromDate).
Your code is wrong because you are creating a date formatter configured for your output date string format and trying to use it to convert your input date string to an NSDate.
I am not an expert on NSDateFormatter date strings. Any time I need to work with them I have to dig out the docs and figure out the solution to the specific problem I'm trying to solve. Thus I'm going to leave that part of the problem to you. Suffice it to say that you'll need an input date formatter that uses a format string that exactly matches the format of your input date string. This can be tricky because if it isn't exactly correct it simply fails and returns a nil NSDate.
The output date formatter is easier because if it isn't quite right, your output date will not look the way you want it to look but that will be obvious.
Recommend you to use library SwiftDate with dozen of handy options.
For your case use date truncating e.g.:
let date = "2017-07-22 15:03:50".toDate("yyyy-MM-dd HH:mm:ss", region: rome)
let truncatedTime = date.dateTruncated(from: .hour) // 2017-07-22T00:00:00+02:00
For Swift 4 and above, You can go with the following code
let date = "2016-02-10 00:00:00"
let dateFormatter = DateFormatter()
let date = modelDeals.dealItemInDetail?.validTo ?? ""
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let dateFromString : NSDate = dateFormatter.date(from: date)! as NSDate
dateFormatter.dateFormat = "dd-MM-yyyy"
let datenew = dateFormatter.string(from: dateFromString as Date)
For swift : (Swift 3) applications,
if you are using Date() objects make sure you set timeStyle
of DateFormatter() to none
Example:
let today = Date()
let dateFormatter = DateFormatter()
//dateFormatter.dateFormat = "yyyy-MM-dd", upto you
dateFormatter.dateFormat = "dd-MM-yyyy"
//This is Important!
dateFormatter.timeStyle = DateTimeFormatter.Style.none
let dateString = dateFormatter.string(from: today)
Swift 3 Version:
let date = "2016-02-10"
let dateformater = DateFormatter()
dateformater.dateFormat = "YYYY-MM-dd"
let dateString = dateformater.date(from: date)
//print date
print(dateString)
I want to display calendar in this format
to the user. One option is to use "string range" to get the individual calendar components. The second one is to get it using NSCalendar which to me looks like the better one (is it?). So my code is as below. But there are two problems.
I am not getting the local time form "hour & minute components"
I am getting month in Int. I want it to be in String (month in mediumStyle)
Anyone know how to get what I need? Image attached is what exactly I want to achieve. There I am using three UILabel one for "date", second for "month, year" and third for "time".
Any help would be appreciated.
var inputDateString = "Jun/12/2015 02:05 Am +05:00"
override func viewDidLoad() {
super.viewDidLoad()
let newDate = dateformatterDateString(inputDateString)
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: newDate!)
let hour = components.hour
let minutes = components.minute
let month = components.month
let year = components.year
let day = components.day
println(newDate)
println(components)
println(day) // 12
println(month) // 6 -----> Want to have "Jun" here
println(year) // 2015
println(hour) // 2 ------> Want to have the hour in the inputString i.e. 02
println(minutes) // 35 ------> Want to have the minute in the inputString i.e. 05
}
func dateformatterDateString(dateString: String) -> NSDate? {
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM/dd/yyyy hh:mm a Z"
// dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
dateFormatter.timeZone = NSTimeZone.localTimeZone()
return dateFormatter.dateFromString(dateString)
}
You can use DateFormatter as follow:
extension Formatter {
static let monthMedium: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "LLL"
return formatter
}()
static let hour12: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "h"
return formatter
}()
static let minute0x: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "mm"
return formatter
}()
static let amPM: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "a"
return formatter
}()
}
extension Date {
var monthMedium: String { return Formatter.monthMedium.string(from: self) }
var hour12: String { return Formatter.hour12.string(from: self) }
var minute0x: String { return Formatter.minute0x.string(from: self) }
var amPM: String { return Formatter.amPM.string(from: self) }
}
let date = Date()
let dateMonth = date.monthMedium // "May"
let dateHour = date.hour12 // "1"
let dateMinute = date.minute0x // "18"
let dateAmPm = date.amPM // "PM"
NSDateFormatter has monthSymbols, shortMonthSymbols and veryShortSymbols properties.
So try this:
let dateFormatter: NSDateFormatter = NSDateFormatter()
let months = dateFormatter.shortMonthSymbols
let monthSymbol = months[month-1] as! String // month - from your date components
println(monthSymbol)
I am adding three types. Have a look.
//Todays Date
let todayDate = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: todayDate)
var (year, month, date) = (components.year, components.month, components.day)
println("YEAR: \(year) MONTH: \(month) DATE: \(date)")
//Making a X mas Yr
let morningOfChristmasComponents = NSDateComponents()
morningOfChristmasComponents.year = 2014
morningOfChristmasComponents.month = 12
morningOfChristmasComponents.day = 25
morningOfChristmasComponents.hour = 7
morningOfChristmasComponents.minute = 0
morningOfChristmasComponents.second = 0
let morningOfChristmas = NSCalendar.currentCalendar().dateFromComponents(morningOfChristmasComponents)!
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
let dateString = formatter.stringFromDate(morningOfChristmas)
print("dateString : \(dateString)")
//Current month - complete name
let dateFormatter: NSDateFormatter = NSDateFormatter()
let months = dateFormatter.monthSymbols
let monthSymbol = months[month-1] as! String
println("monthSymbol : \(monthSymbol)")
Print Results:
YEAR: 2015 MONTH: 10 DATE: 9
dateString : December 25, 2014 at 7:00:00 AM
monthSymbol : October
Update Swift 5.x Solution:
Today is Monday, 20 April, 2020
let date = Date() // get a current date instance
let dateFormatter = DateFormatter() // get a date formatter instance
let calendar = dateFormatter.calendar // get a calendar instance
Now you can get every index value of year, month, week, day everything what you want as follows:
let year = calendar?.component(.year, from: date) // Result: 2020
let month = calendar?.component(.month, from: date) // Result: 4
let week = calendar?.component(.weekOfMonth, from: date) // Result: 4
let day = calendar?.component(.day, from: date) // Result: 20
let weekday = calendar?.component(.weekday, from: date) // Result: 2
let weekdayOrdinal = calendar?.component(.weekdayOrdinal, from: date) // Result: 3
let weekOfYear = calendar?.component(.weekOfYear, from: date) // Result: 17
You can get an array of all month names like:
let monthsWithFullName = dateFormatter.monthSymbols // Result: ["January”, "February”, "March”, "April”, "May”, "June”, "July”, "August”, "September”, "October”, "November”, "December”]
let monthsWithShortName = dateFormatter.shortMonthSymbols // Result: ["Jan”, "Feb”, "Mar”, "Apr”, "May”, "Jun”, "Jul”, "Aug”, "Sep”, "Oct”, "Nov”, "Dec”]
You can format current date as you wish like:
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let todayWithTime = dateFormatter.string(from: date) // Result: "2020-04-20 06:17:29"
dateFormatter.dateFormat = "yyyy-MM-dd"
let onlyTodayDate = dateFormatter.string(from: date) // Result: "2020-04-20"
I think this is the most simpler and updated answer.
Swift 4.x Solution:
//if currentMonth = 1
DateFormatter().monthSymbols[currentMonth - 1]
Answer:
January
let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL"
let nameOfMonth = dateFormatter.string(from: now)