I set the minimum date in the date picker like so:
override func viewDidLoad() {
super.viewDidLoad()
datePicker.minimumDate = NSDate()
}
This does prevent the user from rolling back the date, sort of. The user can roll the date dial back but it just snaps back to the current date. The problem is that when this happens, the datetime is set to midnight instead of the current time for any and all future changes and it also executes the event that runs when the date changes. This is a problem when it comes to my code and sliders in my UI. It thinks that the date changed when it did not, yeah it bounces back but it's too late by this point my code runs assuming the date changed. How do I prevent the user from rolling the dial back at all?
Steps to reproduce:
1) Set minimum date as shown above.
2) Set up an event for date change
3) Set event to print(datePicker.date)
4) Roll Dial forward
5) Roll dial backward beyond current date.
6) Roll dial forward
Notice the time is now permanently set to midnight from this point forward.
A quick fix/workaround was to set datePicker.date = NSDate() in the date changed event function.
Related
I currently have the following use case:
User receives a date in UTC from the backend
This date is transformed into local time for displaying purposes
The date is displayed in different inputs. One input for date and other for time
User can select time independently
The date should be sent back to the backend in UTC format as well
I'm not very experienced with time zones and I'm getting beaten by trying to allow the user to set up only the time (or date) in a datetime field.
My pseudo code is the following:
When receiving the from backend simply convert the date to show it to the user, making the orignal date stay in UTC
When the user picks the hour and minute (all in one action) use setHours and setMinutes from date-fns library
Use native toISOString() to set in models
Code so far [playground]:
import { utcToZonedTime, format } from "date-fns-tz";
import { setHours, setMinutes } from "date-fns";
const UTCStringdate = "2022-04-06T10:00:00.000000Z";
const userTimezone = "Asia/Bangkok";
const localizedTime = utcToZonedTime(UTCStringdate, userTimezone);
// Prints the correct information
// 10:00 in UTC is equal to 17:00 in Bangkok
console.log(format(localizedTime, "HH:mm"));
// Now I expext to set only the `minutes` and `hours`
// to this `localizedTime` so that I can update the backend
const [hours, minutes] = "10:30".split(":");
// Somewhere over here the `setHours` and `setMinutes`
// is turning the Date object into my own timezone
// and not using `Asia/Bangkok` timezone anymore
let newTime = setHours(localizedTime, hours);
newTime = setMinutes(newTime, minutes);
// Now I expect to print 17:30 since we only
// set up 30 minutes forward than the original one
// but it ends up printing 10:30
console.log(format(newTime, 'HH:mm'));
I understand that somewhere along the way (most likely in setHours and setMinutes) the date-fns library turns back the localizedTime back into my own timezone, completely ruining the idea of turning the Asia/Bangkok time into UTC.
Questions
First, is this the best approach to manipulate only the time part of a date when considering timezones? If not, anyone can point me to articles? I wasn't able to find anything on the topic
Second, how can I use setHours and setMinutes and still maintain the timezone?
There are no multiple time zones in JavaScript. There is UTC and there is your local one. What date-fns-tz does, is adjusting the time to the chosen user time zone. In your example, you can see this when printing both the original and the localized time
const utcTime = new Date(UTCStringdate);
console.log(utcTime.toISOString()); // -> 2022-04-06T10:00:00.000Z
console.log(localizedTime.toISOString()); // -> 2022-04-06T14:00:00.000Z
To solve your issue, convert UTC time to users time and let the user to adjust hours and minutes in his local time zone. After that, convert the time object back to UTC using zonedTimeToUtc
newTime = zonedTimeToUtc(newTime, userTimezone);
and then use newTime.toISOString() to send it back to the server.
console.log(newTime.toISOString());
I'm working on a project in which the user can select a time interval (HH:mm) from a UIDatePicker in count down mode and, with that time interval, I want to trigger a notification.
I created the UIDatePicker in the Storyboard and set the Mode to Count Down Timer in the Attributes Inspector.
The problem is that when I get the current value of the datePicker, the value is never correct.
For example, if the user selects 1 minute, I get random values between 70 an 110 but never 60!
How is this possibile?
(The problem occurs with every selection)
This is how I get the current value:
timePicker.countDownDuration
and for testing purpose, I print it with
timePicker.countDownDuration.description
Maybe there is a bug or something that I don't know? (of course there is)
I tried to convert the value represented on the UIDatePicker in string a then, reconvert it in TimeInterval but if there is a better method it would be great.
Ok problem solved, maybe it's a bug of XCode.
The problem occurs when you build the datepicker from storyboard and set it's mode paramether to Count Down Timer.
To solve this problem, simply don't set the mode of the datepicker on count down timer from the storyboard but you need to set the mode programmatically with
timepicker.datePickerMode = .countDownTimer
Doing this, the problem is solved
This question is best stated in an example:
It is currently 9:00am. User wants to do activity at 4:00pm the following day. They use UIDatePicker to select 4:00pm the next day, and then hit a button. I know firebase does times in milliseconds from 1970, so what I want to do is "add" the number of milliseconds from 9:00am to 4:00pm the following day to the ServerValue.timestamp(), like so:
activitiesRef.child(newActivity.id).setValue([
"id": newActivity.id,
"name": newActivity.name,
"isActive": newActivity.isActive,
"locString": newActivity.locationString,
"locLat": newActivity.locLat,
"locLong": newActivity.locLong,
"privacySetting": newActivity.privacySetting,
"targetTime": ServerValue.timestamp()]) // + some added value of time
//"targetTime": [".sv": "timestamp"]])
The reason for this is because I will be displaying a countdown timer elsewhere in the app until it reaches the targetTime. If I can push to firebase the targetTime, then the countdown timer will be a simple comparison of the current time on the user's phone to the targetTime itself.
The error I keep getting when trying to add a double value to the ServerValue.timestamp() is "Contextual type 'Any' cannot be used with dictionary literal"
If it is not possible to do so, what other options do I have? Thank you.
ServerValue.timestamp() is not a number that you can use to perform date arithmetic. It's a special placeholder value that the server side interprets with its sense of time.
The best you can do is write the timestamp, read it back out as a number, then perform math on it.
My current project is a timer which uses a date picker to set the amount of time the user wants before the timer goes off (say 1 minute, 6 hours and two minutes etc.). The problem lies in the amount of time that the date picker believes it has been set for. Below is the code which I am using to set the time.
#IBOutlet weak var datePicker: UIDatePicker!
var timeAmount:Double = 0
#IBAction func startButton() {
timeAmount = Double(datePicker.countDownDuration)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeAmount, repeats: false)
}
Here it can be seen that the function startButton, sets the value of timeAmount to be the amount of time that the date picker is set for. This timeAmount value is then used in a local notification as the time.
The issue is that the datePicker.countDownDuration is never correct. If it is set for one minute, then timeAmount may return a value of 99 seconds, 62 seconds, 67 seconds etc. It is just completely random.
Maybe I do not entirely understand how the .countDownDuration feature works, however from everything I have read, this should return a value of 60 seconds.
Any thoughts and suggestions on the matter will be very much appreciated, thank you.
By default, the UIDatePicker will take the current second value for the calculation.
timeAmount = (number of minutes selected in picker * 60) + current time second value.
For example:
If the current time is 13:40:25 (1 PM 40 minutes 25 seconds) and you have selected one minute in the date picker, the value of timeAmount in this case is 85.
timeAmount = (1*60) + 25
This will solve your problem.
Go to your Storyboard and select UIDatapicker. Navigate to Date option in Attributes inspector.
Click the Dropdown and change it to Custom from Current Date.
You will see a new text field with the current time as the custom date.
Just change the second field to 00.
Run the App now. Now it will take 0 as the value for the second and you will able to see seconds value correctly based on the time you are choosing in the date picker.
Hope this will solve your problem.
I've come across a small issue that I've been chewing on for a day or two now.
Using the Apple example project called DateCell I lifted its UIDatePicker and set it to time. I used this particular code as it did the animated slide on/off the screen.
My workflow is to set four values, start time, lunch time out, lunch time in, and stop time. I set these values by using [NSDate date].
I then use NSCalander:component calls to do some math such as "add 30 minutes to start time to get lunch time out," and "start time - lunch time out - 8 hours to get stop time."
The initial setup goes just fine. Clicking on the start time cell brings up the picker, and selecting a time change the other three times following my simple math formula's.
If the second row is selected, the lunch time out, the wheel comes up again to pick your lunch time out time. However this is where my problems start. It seems that my UIDatePickerModeTime wheel returns a date portion for January 1, 1970. And its this date portion that messes up my math formulas.
My question is, what can I do to fix this?
I've tried setting an initial, minimum time, in the XIB for the picker. This sort of works but when you pick a time on the wheel, the wheel spins itself to the time set in the XIB. This method doesn't have a clean feel to it.
I've tried settings the initWithTimeInterval class methods, but these block out times and isn't what I'm looking for I think.
I've also tried the NSDateFormatter:stringFromDate|dateFromString calls, and these had no affect.
What I have not done yet:
Custom defined date/time string.
Rebuilding UIDatePicker:Time from scratch
Am I over looking anything?
Thanks.
I've solved my problem, and here is how I addressed it.
Before I get to my answer I'm still really new to Objective-C and object oriented programming so my vocabulary doesn't know how to describe some of the things I've tried explaining. So take this into account when reading this.
Using UIDatePicker in time mode, i.e. you go into your NIB/XIB file and set your UIDatePicker object to 'time', will only return time. This is where I went wrong.
Using the NSDateComponent or any of the NSCalendar methods will bring out the date component of the picker. Thus you'll see January 1st, 1970 in the NSLog returns for example.
I had to find a new way of doing my math and manipulation of the times I was getting from the picker.
What I ended up using is NSTimeInterval, dateByAddingTimeInterval, and timeIntervalSinceDate. Research showed that NSTimeInterval is also a float type, so I used float to do some math as well.
Here an example -
if (indexPath.row == [labelArray indexOfObjectIdenticalTo:#"Clock Out"])
{
NSTimeInterval diffClockInOutToLunch = [outToLunch timeIntervalSinceDate:clockIn];
float remainingInTheDay = 28800 - diffClockInOutToLunch;
self.clockOut = [inFromLunch dateByAddingTimeInterval:remainingInTheDay];
cell.detailTextLabel.text = [self.dateFormatter stringFromDate:clockOut];
self.clockOutIndex = indexPath;
return cell;
}
I'm using a TableView to display my fields. When this 'if' statement is tripped it will populate the detailTextLabel of the line displaying "Clock Out." Visually the phrase "Clock Out" will be on the left side of the row, the time will be on the right side.
diffClockInOutToLunch is defined as a NSTimeInterval type. The operation being performed is timeIntervalSinceDate which essentially subtracts the value of outToLunch from the value of clockIn. Imagine outToLunch as being 11:00pm and clockIn as being 6:00am. This difference is 5 hours. NSTimeInterval stores values as seconds only so this difference of 5 hours is 18000 seconds.
I then perform a normal math operation using float. In this case I want to find out how many hours remain in the work day. This assumes the hours worked in a day is 8 hours. Because NSTimeInterval returns seconds, I converted 8 hours into seconds (28,800 seconds) and then subtract diffClockInOutToLunch from 28800. Now remainingInTheDay is equal to to 10800, or 3 hours.
The next operation I perform is set clockOut to the time our work day is finished. To do this I use the dateByAddingTimeInterval operation, which also is a NSDate method, so whatever it returns will be in a date/time format. In this operation we add remainingInTheDay (10,800 seconds) to inFromLunch (11:30am for example). Our clockOut time is now 2:30pm which is then sent through my DateFormatter and returned as a string to the cell of the TableView and also stored for later use.
Here's another example, from further down in my code -
- (void)clockInChanged
{
// Set clockIn value
self.clockIn = self.pickerView.date;
// Change the outToLunch time
self.outToLunch = [self.pickerView.date dateByAddingTimeInterval:5*60*60];
UITableViewCell *outToLunchCell = [self.tableView cellForRowAtIndexPath:outToLunchIndex];
outToLunchCell.detailTextLabel.text = [self.dateFormatter stringFromDate:outToLunch];
// Change the inFromLunch time
self.inFromLunch = [outToLunch dateByAddingTimeInterval:30*60];
UITableViewCell *inFromLunchCell = [self.tableView cellForRowAtIndexPath:inFromLunchIndex];
inFromLunchCell.detailTextLabel.text = [self.dateFormatter stringFromDate:inFromLunch];
// Change the clockOut time
NSTimeInterval diffClockInOutToLunch = [outToLunch timeIntervalSinceDate:clockIn];
float remainingInTheDay = 28800 - diffClockInOutToLunch;
self.clockOut = [inFromLunch dateByAddingTimeInterval:remainingInTheDay];
UITableViewCell *clockOutCell = [self.tableView cellForRowAtIndexPath:clockOutIndex];
clockOutCell.detailTextLabel.text = [self.dateFormatter stringFromDate:clockOut];
}
In this example, we've previously determined that the row pertaining to "Clock In" time was selected ("Touch Up Inside" if you will) and we drop to this method.
What happens in this method is whenever clockIn is changed using the picker, the times displayed in outToLunch, inFromLunch, and clockOut automatically update and are displayed.
This example shows that we capture the value on the picker (self.pickerView.date) as clockIn. We then use clockIn to seed our mess of dateByAddingTimeInterval's and so forth.
So. This is how I managed my times using UIDatePicker (which is set to time mode).
The short answer would be I was using the wrong methods to work with what my picker was turning.
I hope this helps you and hopefully it'll be here if I need it again too ;)