Is there a way of getting the first day of the week from device info or locale in Flutter? I use some libraries for which it has to be manually set, so I need to get it somehow. Or maybe, at least, these is even a library you might know which returns first day of the week by locale code?
You can use subtract method to get first day of the week according to user's device locate
DateTime today = DateTime.now();
_firstDayOfTheweek = today.subtract(new Duration(days: today.weekday));
Or you can do that with material localization and get it from context
MaterialLocalizations.of(context).firstDayOfWeekIndex;
Related
Is there any way to check if the system DateTime is correct or not in Flutter? I tried searching for APIs which provide current DateTime, but the problem with timezones happens again. What is the solution for this? (I want to do something like WhatsApp. which is, don't give chatting access if system DateTime is wrong)
you can use ntp plugin
var nowInternet = await NTP.now();
var now = DateTime.now();
print(nowInternet);
print(now);
//check diff is grater than 1 minute
if (nowInternet.difference(now).inMinutes < 1){
//good
}
simple solution, use unix epoch time
print(DateTime.now().millisecondsSinceEpoch);
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 trying to parse a string into a DateTime in flutter.
On android, iOS and Web the procedure works perfectly, but on windows it keeps returning, only at midnight, the wrong time.
DateFormat('HH:mm').parse('00:25');
returns 1970-01-01 01:25:00.000 on windows, but 1970-01-01 00:25:00.000 on any other OS, while any hour >= 1 returns the right value.
If I try using parseStrict method, the following happens
DateFormat('HH:mm').parseStrict('00:25');
returns FormatException: Error parsing 00:25, invalid hour value: 0 in it with time zone offset 1:00:00.000000. Expected value between 1 and 1. Date parsed as 1970-01-01 01:25:00.000..
Thanks in advance for any help
Edit: This DateTime is in local timezone, I'm not trying to parse a UTC time. I've noticed, though, that if I add the date, the DateTime seems to get parsed properly.
But I need only the time.
These values are the open hours for a shop.
I know that I SHOULD use TimeOfDay class, but I can't use it because it doesn't have the compareTo method, which I need for my case scenario.
Anyway, I've tried Android, iOS and Web and they all parse the time properly, the only one problematic is Windows
I'm trying to use an NSDatePicker to set a time when an event should happen. Unfortunately, however, this control is used to set a complete date and therefore it is possible that when I have to use the value, it belongs to the past. My goal is to use the datePicker to set a time in the future.
To create a future date preserving this time I tried to set a loop that adds a day until we get to a future point but this seems to be very expensive in terms of time and processing, or I tried to manually build a date using only time. Unfortunately, I do not think I have found a viable solution because of my lack of experience on the subject.
Here is the code I am using:
// getting date value from a NSDatePicker
let date = myDatePicker.dateValue
// learn if the date is in future or in past
if date.timeIntervalSince(currentDate as Date).sign == FloatingPointSign.minus {
print("\(date) is in past") // update adding days to make it in future
// get the hour and minute from the date
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "HH:mm" // only hour and second
let timeString = timeFormatter.string(from: date as Date)
print("\(timeString)") // here I get "18:10" or "6:10 PM" based on system preferences (12 or 24)
// create a date in future that use this hours
} else {
// the date is already in future, just use it
...
}
I found several questions here on Stack Overflow, that are helping me to better understand how to use NSDateFormatter and also a great online tutorial http://www.knowstack.com/swift-nsdateformatter/. I also found some questions that seems similar to mine, like: returns a date an hour in the future and init] returning date an hour in the past? but they did not help me.
Apple Developer Documentation:
NSDatePicker
NSDateFormatter
i am New to iphone Development .I Am Trying To Use NslocalNotification In My Project I Need To Give Remeinder For Every 2Hours or For Every Two Days Or For Every Two Months Etc..Currently I am Using NslocalNotification Repeat Interval .But Its Working For Only Every Minute For Every Hour using Nscalender ....
NSString *InterVal=[freQuencyArr objectAtIndex:index-2];
NSString *InterValType=[freQuencyArr objectAtIndex:index-1];
if(![InterVal isEqualToString:#"Every"])
{
result=[InterVal intValue];
}else
result=1;
if([InterValType isEqualToString:#"Day"]){
notification.repeatInterval= NSDayCalendarUnit;
}else if([InterValType isEqualToString:#"Week"]){
notification.repeatInterval= NSWeekCalendarUnit;
}
else if([InterValType isEqualToString:#"Month"]){
notification.repeatInterval= NSMonthCalendarUnit;
}else if([InterValType isEqualToString:#"days"]){
notification.repeatInterval=result*24*60*60;
}
here If result is 2 depend Up on IntervalType I Need Notification
its Not Working With Me
if([InterValType isEqualToString:#"days"]){
notification.repeatInterval=result*24*60*60;
}
#Srinivas:
If you look at the link I have posted in this answer, You will come to know that I have tried every possible solution here to try and do what you want currently.
I had tried all this to implement it in my app, but this doesn't work.
I am afraid to say this but this is not possible. It only allows the unit NSCalendarUnit objects to be set as a repeat interval.
I invested almost 2 months (I asked the question in Dec 2010 and answered it myself in February 2011) to try and implement every possible solution available on internet through different articles and different forums but none did help.
Check out my link and lookout for all the answers if something is useful to you.
How to set Local Notification repeat interval to custom time interval?
Really Hope that this helps you.
The repeatInterval property of a UILocalNotification cannot be used to repeat less than every one calendar unit, i.e. every day, every week, every month, etc.
Instead, you will have to schedule multiple notifications to achieve the desired effect, setting the fireDate property accordingly.
As lemnar says you are unable to use repeatInterval to repeat in a frequency different from the calendar units Apple provided. So, the code below:
if([InterValType isEqualToString:#"days"]){
notification.repeatInterval=result*24*60*60;
}
Will not do anything. I am also using repeat notifications in an app that I have built and the way I've gotten around this is by creating multiple notifications each repeating to give the "desired" repeat frequency. As an example, if I want to repeat "every 2 days", I can't do this using repeatInterval. However, I have a "scheduling function" in my app that creates multiple individual notifications to achieve this. I do this going out an arbitrary length of time (in my case, one week). So in the example above, when the user specifies that he / she needs a notification every two days from today, I create 3 notifications (one each for day 3, 5, and 7).
For repeating at a frequency less than a calendar unit, things are a little easier. Say I need to repeat every 12 hours (at 6AM and 6PM). Then, I would create 2 notifications (one for 6AM and another for 6PM). I would then set the repeatInterval for each of these notifications to NSDayCalendarUnit. This way I have created a set of notifications that repeat every 12 hours.
When my app loads, I go out another 7 days and recreate notifications as needed. Not the most elegant solution, but this was the best way I could think of getting around the repeatInterval limitation.