Date to String => Time is missing - datepicker

I am trying to convert date to string so I can save this data in firestore. But my getDate func is getting only today's date, not the time
struct NewTaskView: View {
#State var taskTitle = ""
#State var taskFrom = ""
#State var taskFromDate = Date()
var body: some View {
NavigationView {
VStack(alignment: .leading) {
Group { // Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
Text("Task Title")
TextField("Title", text:$taskTitle )
Divider()
Text("From")
DatePicker("", selection: $taskFromDate, in: Date()...)
.labelsHidden()
.onReceive(Just(taskFromDate)) { data in
taskFrom = getDate(date: taskFromDate)
}
Divider()
} .padding(.horizontal, 10)
.font(Font.custom("SFCompactDisplay-Bold", size: 25))
.foregroundColor(.gray)
func getDate(date: Date) -> String {
let formatter = DateFormatter()
formatter.dateStyle = .full
let dateTime = formatter.string(from: date)
return dateTime
}

func getDate(date: Date) -> String {
let formatter = DateFormatter()
formatter.dateStyle = .full
formatter.timeStyle = .short
let dateTime = formatter.string(from: date)
return dateTime
}

You can use the following function:
func getDate(date:Date) -> String{
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
let updatedAtStr = "2016-06-05T16:56:57.019+01:00"
let updatedAt = formatter.date(from: updatedAtStr)
let result = "\(updatedAt!)".split(separator: " ")
return String(result[0]+" "+result[1])
}

Related

How to change a string I get from API

I get a string with a date of the first flight for each of four rockets from this API. The string that I get looks like this: "2006-03-24". I want it to look this way: "24 March, 2006". I don't understand how to do this in SwiftUI.
My View with the dates:
struct DateView: View {
#State var rockets = [RocketInfo]()
var body: some View {
NavigationView {
if rockets.isEmpty {
ProgressView()
} else {
TabView {
ForEach(rockets) { rocket in
VStack {
HStack {
Text("First flight")
Spacer()
Text(rocket.firstFlight)
}
.padding()
}
}
}
.tabViewStyle(.page)
.navigationBarTitleDisplayMode(.inline)
.navigationBarHidden(true)
}
}
.onAppear {
InfoApi().getRockets { rockets in
self.rockets = rockets
}
}
}
}
struct DateView_Previews: PreviewProvider {
static var previews: some View {
DateView()
.preferredColorScheme(.dark)
}
}
Screenshot of the API data: enter image description here
The func gets a date from the string, which you then can format to your wishes.
var body: some View {
let dateString = "2006-03-24"
let date = dateFromString(dateString)
Text("\(date, style: .date)")
}
func dateFromString(_ string: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.locale = .current
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from: string) ?? Date()
}
You'll need two instances of DateFormatter - one to convert the string from API to a Date instance and the other to convert the date instance to your desired string format.
let dateFormatter1 = DateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd" // Format of API Date
let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "d MMMM, yyyy" // Desired Format
let date = dateFormatter1.date(from: "2006-03-24")!
let desiredFormat = dateFormatter2.string(from: date)
print(desiredFormat) // prints "24 March, 2006"
First, I encourage you to change firstFlight in RocketInfo to be a Date object, to get the correct data representation in the model. You may have to configure your JSONDecoder to parse the date string correctly:
let decoder = JSONDecoder()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
decoder.dateDecodingStrategy = .formatted(formatter)
Then, you need another DateFormatter when you want to convert that date back into a string:
let formatter = DateFormatter()
formatter.dateFormat = "d MMMM, yyyy"
let dateString = formatter.string(from: object.firstFlight)
Please see here for the list of custom formats supported by DateFormatter:
http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns
(There's also a couple of system defined formats, please see dateStyle and timeStyle in the docs.)

How can I specify some days to be available for reservation swiftui or UIKit

How can I specify some days to be available for reservation in : swiftui , UIKit or if have any way in Firebase
this is Example:
day : 16,17,18,20 is available in
struct Test4: View {
let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter
}()
let dateFormatter2: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd, MMMM, yyyy"
return formatter
}()
#State private var reservationDate = Date()
var body: some View {
VStack {
DatePicker("", selection: $reservationDate, in: Date()..., displayedComponents: .date)
.datePickerStyle(GraphicalDatePickerStyle())
Spacer()
Text("\(reservationDate, formatter: dateFormatter2)")
.font(.title)
.bold()
Spacer()
}
}
}

Segmentation 11 non zero exit code error in SwiftUI in Xcode

error: Segmentation fault: 11 (in target 'ProjectName' from project 'ProjectName')
Command CompileSwift failed with a nonzero exit code
Both of these errors are present when the following file is in my project:
import Foundation
import SwiftUI
import Mapbox
class TimeFetcher: ObservableObject {
#Published var startTime: String = ""
#Published var endTime: String = ""
#Published var eventdate: String = ""
#Published var annotation: MGLAnnotation?
#Published var eventdate: String = ""
#Published var date: Date? = Date()
#Published var startTimeDateObject: Date? = Date()
#Published var endTimeDateObject: Date? = Date()
var data: DataFetcher
var inputDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" // <- do not escape `Z` (time zone)
return formatter
}()
var outputDateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.setLocalizedDateFormatFromTemplate("EEEE MMMM yyyy d") //hh mm")
return formatter
}()
var outputTimeFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.timeZone = TimeZone.current
formatter.setLocalizedDateFormatFromTemplate("hh mm")
return formatter
}()
var formattedDate: String {
date != nil ? self.outputDateFormatter.string(from: date!) : "Date is nil"
}
var formattedStartTime: String {
startTimeDateObject != nil ? self.outputTimeFormatter.string(from: startTimeDateObject!) : "Date is nil"
}
var formattedEndTime: String {
endTimeDateObject != nil ? self.outputTimeFormatter.string(from: endTimeDateObject!) : "Time is nil"
}
func setStartAndEndTimes() {
for event in self.data.events {
print("the selectedannotation title is \(annotation.title) and the event address is \(annotation.address)")
if self.annotation.title == event.address {
print("the start time is initially \(self.startTime)")
self.startTime = event.start_time
print("the start time at the end is \(self.startTime)")
self.endTime = event.end_time
}
}
}
func parseDate() {
let dateStr = self.eventdate
if let date = self.inputDateFormatter.date(from: dateStr) {
self.date = date
} else {
print("invalid date")
}
// alternatively if you don't care about errors:
// date = Self.dateFormatter.date(from: dateStr)
}
func parseStartTime() {
let dateStr = self.startTime
if let date = self.inputDateFormatter.date(from: dateStr) {
self.startTimeDateObject = date
} else {
print("invalid date")
}
// alternatively if you don't care about errors:
// date = Self.dateFormatter.date(from: dateStr)
}
func parseEndTime() {
let dateStr = self.endTime
if let date = self.inputDateFormatter.date(from: dateStr) {
self.endTimeDateObject = date
} else {
print("invalid date")
}
// alternatively if you don't care about errors:
// date = Self.dateFormatter.date(from: dateStr)
}
}
Also when I declare the object in my content view init, I get a weird error where it says 'TimeFetcher' cannot be constructed because it has no accessible initializers'
init() {
let vm = ViewModel()
VModel = vm
annotationsVM = AnnotationsVM(VModel: vm)
locationManager = LocationManager()
data = DataFetcher()
timeData = TimeFetcher(data: data)
}
#State and #ObservedObject should only be in a View
https://developer.apple.com/documentation/swiftui/state
https://developer.apple.com/documentation/swiftui/observedobject
Stick with #Published for all the #State and remove the #ObservedObject you don't need it in a non-View class.

Time and date formatter SwiftUI JSON data

Hopefully this an easy one. Im trying to display the date and time in a list In an iOS application using SwiftUI. I'm having issues with the code at the moment and getting this error message: Cannot convert value of type 'PostListViewModel' to expected argument type 'Data'
Please find the code below:
struct PostViewModel {
var post: Post
init(post: Post) {
self.post = post
}
var startTime: Date {
let data = PostListViewModel()
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(DateFormatter.DateFormat)
let postDate = try! decoder.decode(startTime.self, from: data)
return self.post.startTime
}
}
extension DateFormatter {
static let DateFormat: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "MMM d"
formatter.calendar = Calendar(identifier: .iso8601)
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
return formatter
}()
}
Can you see any issues with the code?
If you want to convert a date string to a Date and then to another date string use one date formatter with two different date format strings
struct PostViewModel {
var post: Post
init(post: Post) {
self.post = post
}
var startTime: String {
let formatter = DateFormatter()
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
if let date = formatter.date(from: post.startTime) {
formatter.dateFormat = "MMM d"
return formatter.string(from: date)
} else {
return post.startTime
}
}
}

Cannot convert value of type 'String' to expected argument type 'TimeInterval' (aka 'Double')

I am formatting time that is being passed in. I am getting this error, and I'm trying to figure out what's happening here with it. I'm using the most up to date version of Xcode (v. 8) and am programming in Swift 3. What this error means and how to fix it?
I'm piecing in parts of the code that are relevant to the question so it's not a overload of information here.
var date: String {
if _date == nil {
_date = ""
}
return _date
}
init(weatherDict: Dictionary<String, AnyObject>){
if let temp = weatherDict["temp"] as? Dictionary<String, AnyObject>
{
if let min = temp["min"] as? Double{
self._lowTemp = ktof(kelvins: min)
}
if let max = temp["max"] as? Double{
self._highTemp = ktof(kelvins: max)
}
}
let unixConvertedDate = Date(timeIntervalSince1970: date)
if let date = weatherDict["dt"] as? Double {
let unixConvertedDate = Date(timeIntervalSince1970: date)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
//dateFormatter.dateFormat = "EEEE"
dateFormatter.dateStyle = .none
self._date = unixConvertedDate.dayoftheWeek()
}
}
and then outside of the class, which all the above code is inside of, I have this.
extension Date {
func dayoftheWeek() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self)
}
}
if let date = weatherDict["dt"] as? Double {
let unixConvertedDate = Date(timeIntervalSince1970: date)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.dateFormat = "EEEE"
dateFormatter.timeStyle = .long
self._date = "\(unixConvertedDate)"
}
}
}
extension Date {
func dayOfTheWeek() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self)
}
}