I am relative new to Flutter. While I was experimenting, I came across with an issue. My REST Api takes a timezone parameter (Zone ID format such as Europe/London).
I saw both https://pub.dartlang.org/packages/flutter_native_timezone and https://pub.dartlang.org/packages/timezone, but neither of those serve my needs.
My goal is, when the user connect to the internet (without giving any location access to the app, if it is possible), get the timezone in ZoneId format and feed my back end in order to make the necessary date and time adjustments. Something similar to this
>>> var timezone = jstz.determine();
>>> timezone.name();
"Europe/London"
Presented in https://bitbucket.org/pellepim/jstimezonedetect
Any insights will be really helpful.
Thanks in advance
I've been also looking for this and here's what I found: https://pub.dev/packages/flutter_native_timezone
It a bit hacky under the hood, but it seems to work properly on both iOS and Android. Hope this will help someone in need.
Usage:
final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
print(currentTimeZone); // Europe/Moscow
Came up with a simple solution:
//server time(UTC)
String date_to_parse = "2019-06-23 12:59:43.444896+00:00";
DateTime server_datetime = DateTime.parse(date_to_parse);
//get current system local time
DateTime local_datetime = DateTime.now();
//get time diff
var timezoneOffset = local_datetime.timeZoneOffset;
var time_diff = new Duration(hours: timezoneOffset.inHours, minutes: timezoneOffset.inMinutes % 60);
//adjust the time diff
var new_local_time = server_datetime.add(time_diff);
After doing some digging, I found a (temporary) workaround to my issue.
Using
var now = new DateTime.now();
var timezoneOffset = now.timeZoneOffset;
I got the timezoneOffset in UTC format in flutter. Then send it to my back end as string (i.e. "-04") and drift my ZoneId properly.
Integer tzOffsetHour = Integer.valueOf(covertToTimezone);
ZoneOffset offset = ZoneOffset.ofHoursMinutes(tzOffsetHour, 0);
ZoneId zoneTZ = ZoneId.ofOffset("UTC", offset);
LocalDateTime localDateTimeClient = new Date().toInstant().atZone(zoneTZ).toLocalDateTime();
As a result I take the local time and date as stated in user's device, without using any location services, which was my goal from the beginning.
Until now, I have not faced any issues... we will see...
You can simply add .toLocal() to your DateTime object.
myDate = otherDate.toLocal();
myDate = DateTime.parse(json['server_date']).toLocal();
If you are just after the Time Zone offset. All you need is one line of code
int tzOffset = DateTime.now().timeZoneOffset.inHours;
The best way is to use timezone. as below
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
String getNameLocalTimeZone() {
tz.initializeTimeZones();
var locations = tz.timeZoneDatabase.locations;
int milliseconds=DateTime.now().timeZoneOffset.inMilliseconds;
String name = "";
locations.forEach((key, value) {
for (var element in value.zones) {
if (element.offset == milliseconds) {
name = value.name;
break;
}
}
});
return name;
}
DateTime.now().timeZoneOffset // +5:30:00.000000 is expected format
Related
I use momentJS for date conversion but recently ran into a problem that appears only on iOS when calculating the difference between 2 dates.
I have two strings that looks like this:
const startDate = "08-21-2022 10:28 AM";
const endDate = "08-31-2022 10:28 AM";
In a non iOS system this works:
moment(endDate).diff(moment(startDate), "days")
But on iOS it returns NaN with a warning:
Deprecation warning: value provided is not in a recognized RFC2822 or
ISO format. moment construction falls back to js Date(), which is not
reliable across all browsers and versions. Non RFC2822/ISO date
formats are discouraged and will be removed in an upcoming major
release. Please refer to
http://momentjs.com/guides/#/warnings/js-date/ for more info.
...
I tried the following but without success:
var test1 = moment(dateString);
var test2 = moment(dateString2);
console.log(test2.diff(test1, "days"));
var test5 = moment(dateString).toISOString();
var test6 = moment(dateString2).toISOString();
console.log(moment(test6).diff(moment(test5), "days"));
console.log(moment(dateString).valueOf());
They all seem to return NaN. What can I do to calculate the difference? Even console.log(new Date())
What seems to work is this:
var test3 = moment([2007, 0, 29]);
var test4 = moment([2007, 0, 28]);
test4.diff(test3, "days");
But I'm unsure how I could safely extract the year, I tried these:
var test7 = moment(dateString).year();
console.log("5", test7);
var test8 = moment(dateString).toISOString();
console.log("6", moment(test8).year());
But they all returned NaN;
I have a codesandbox to test on iPhone https://codesandbox.io/s/lively-framework-622p7r?file=/src/App.js
Like the title says, is there a way to get the highs and lows of a stock price during the day after a certain time? There's a way to get the days high and low over a period of time:
=GOOGLEFINANCE("AMZN","high","05/01/2020","05/10/2020","DAILY")
=GOOGLEFINANCE("AMZN","low","05/01/2020","05/10/2020","DAILY")
But what about during the day during a specific time period? For example from 9:12AM PST to 11:23AM PST?
Solution#3 : you can use Alpha Vantage by 2 ways, add-on GSheets or a custom function i.e. :
// mike steelson
var apikey = 'xxxxxxxxxxxxxx'
function getAllDataJSONv2(code) {
var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol='+code+'&interval=5min&apikey='+apikey
var data = JSON.parse(UrlFetchApp.fetch(url).getContentText())['Time Series (5min)']
var resultat = []
for (var elem in eval(data)){
resultat.push([elem,eval(data[elem]['1. open']),eval(data[elem]['2. high']),eval(data[elem]['3. low']),eval(data[elem]['4. close']),eval(data[elem]['5. volume'])])
}
return resultat
}
the apikey is free for up to 500 requests a day. https://rapidapi.com/alphavantage/api/alpha-vantage
no, not possible with GOOGLEFINANCE. you can get only the daily value which is usually from 16:00:00
your only other option is to find some website (which doesn't use JavaScript) that holds values you wish for and scrape it into google sheets
Solution1 : You can use Yahoo Finance to retrieve the information you want
function getHistoric(url){
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString).context.dispatcher.stores.HistoricalPriceStore.prices
var result = []
data.forEach(function(elem){
result.push([elem.date,elem.open,elem.high,elem.low,elem.close])
})
return result
}
https://docs.google.com/spreadsheets/d/1Kly5-Vu5jBfrl6xFljdICFJW369X-OCjB22z3Ouzt4Y/copy
Solution#2 : you can build your own data based on yahoo finance https://docs.google.com/spreadsheets/d/1QlqpPkIMjE8_jT6kNME1cLrMmQZ9cSzG-SR2Jjivvqo/edit?usp=sharing
//Mike Steelson
var histo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('historic')
var code = histo.getRange('B1').getValue()
//put a trigger on historic
function historic(){
if (testDateHour()==true) {histo.appendRow([new Date(),marketPrice(code)])}
}
function marketPrice(code) {
var source = UrlFetchApp.fetch('https://finance.yahoo.com/quote/'+code).getContentText()
var data = JSON.parse(source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}')
return data.context.dispatcher.stores.StreamDataStore.quoteData[code].regularMarketPrice.raw
}
function testDateHour(){
var d = new Date();
// not on sunday and saturday and between 10am and 4pm
if (d.getDay()!=0 && d.getDay()!=6 && d.getHours()>=10 && d.getHours()<=16) {return true}else{return false}
}
Configure your local settings (PST) + update if necessary the period when you want to retrieve the information. Then put the trigger (1min)
I have written a code that subtracts 2 DateTime properties and gives AHT for that task. AHT shows as follows 00:00:00:567, but how can display this as hh:mm:ss format.
Kindly help with this, help is very much appreciated
Below is my Action created.
using(Db db = new Db())
{
Chat newDTO = db.Chats.Where(x => x.ChatId == id).FirstOrDefault();
DateTime startTime = Convert.ToDateTime(newDTO.FeedbackDateTime);
DateTime endtime = Convert.ToDateTime(newDTO.FeedbackSharedDateTime);
TimeSpan duration = endtime.Subtract(startTime);
//hh:mm:ss
string stringAHT = string.Format("{0:D2}:{1:D2}:{2:D2}:{3:D2}",
24 * duration.Days + duration.Hours,
duration.Minutes,
duration.Seconds,
duration.Milliseconds
);
newDTO.AuditorAHT = stringAHT;
db.SaveChanges();
}
Thank you in advance.
Finally made it work
Created AuditorAht field as string data type
In Controller:
string aht = string.Format("0:hh\\:mm\\:ss", dto.datetime1 - dto.datetime2);
dto.AuditorAht = aht;
db.Savechanges();
Now Average Time is storing as hh:mm:ss format as I wanted it to.
I have this dates here:
date1 = 2015-1-1
date2 = 2014-1-1
When I use this code:
int difference = date1.Value.Month - date2.Value.Month
This returns 0. I want the actual result to be 12 months since the date difference is within a year.
Someone help out? Completely new to this.
Try this code
DateTime date1 = Convert.ToDateTime("2015-1-1");
DateTime date2 = Convert.ToDateTime("2014-1-1");
Console.WriteLine((date1.Month - date2.Month) + 12 * (date1.Year - date2.Year));
var difference = date1.Value.Ticks - date2.Value.Ticks;
var dateDifference = new DateTime(difference);
int numberOfMonths = (dateDifference.Years * 12) + dateDifference.Months;
You can't get the exact result since day/years can change but you still
can try this:
//you can determine that the average month has 30.44 days (source:google)
const double daysToMonths = 30.4368499;
DateTime date1 = Convert.ToDateTime("2015-1-1");
DateTime date2 = Convert.ToDateTime("2014-1-1");
//round is optional here
Double Diff = Math.Round(date1.Subtract(date2).TotalDays/daysToMonths,0);
I resolved this issue by adding Microsoft.VisualBasic in my reference and by using the DateDiff function from Visual Basic. By using this, I don't need to manually compute the date anymore, I just set the interval and the 2 dates then it executes perfectly.
DateAndTime.DateDiff(DateInterval.Month, (DateTime)promoevent.TargetStartDate, (DateTime)promoevent.TargetEndDate);
When I submit a CalendarRule to CRM's work hours, the StartTime changes just before it is submitted to the database. I submit the CalendarRule through the code below. The submitted StartTime differ by -2 hours. I suspect this has something to do with the fact that I live in +1 GMT timezone and our clocks are set to dayligt time savings.
var calendarFrequenceRule = new CalendarRule
{
Duration = 24 * 60, //24 hours
ExtentCode = 1,
StartTime = start.Date,
Pattern =
new CalendarRulePattern
{
ByDay = new List<DayOfWeek> {start.DayOfWeek},
Interval = 1,
Frequency = CalendarRulePattern.FrequencyEnum.WEEKLY
}.ToString(),
Rank = 0,
TimeZoneCode = userSettings.TimeZoneCode,
InnerCalendarId = new EntityReference(Calendar.EntityLogicalName, innerCalendarId),
};
calendarRules.Clear();
calendarRules.Add(calendarFrequenceRule);
userCalendarEntity.CalendarRules = calendarRules;
OrganizationService.Update(userCalendarEntity);
var calendarTimeRule = new CalendarRule
{
//Name = name,
//Description = name,
Duration = (int)(end - start).TotalMinutes,
Effort = 1.0,
IsSimple = true,
Offset = (int)(start - start.Date).TotalMinutes,
Rank = 0,
TimeCode = (int)TimeCode.Available,
SubCode = (int)SubCode.Schedulable,
TimeZoneCode = -1,
CalendarId = new EntityReference(Calendar.EntityLogicalName, innerCalendarId),
};
calendarRules.Add(calendarTimeRule);
newInnerCalendar.CalendarRules = new List<CalendarRule> {calendarTimeRule};
OrganizationService.Update(newInnerCalendar);
When I retrieve the time again through the code below the time is off by 4 hours. I've checked that all users have their time zone settings set to the same time zone - but to no avail. When I look at the database I can see that the time zone submitted through code is the same as the calendar rules I've insert through the GUI.
Code to retrieve the CalendarRule:
var user = OrganizationService.Retrieve<SystemUser>(userId);
var expandCalendarRequest = new ExpandCalendarRequest
{
CalendarId = user.CalendarId.Id,
Start = start,
End = end,
};
var response = OrganizationService.Execute<ExpandCalendarResponse>(expandCalendarRequest);
return response.result;
Anytime you insert a DateTime into CRM using the SDK or the Odata endpoint, it assumes that it's UTC. If you update a field via javascript, it will assume it's in the time of the current users. I'm not sure what case you're currently working with, but always work with UTC unless you're editing fields in the actual form.
See this answer: https://stackoverflow.com/a/22787954/227436 for an overview of working with Time in CRM.
This answer has a function that maybe useful in your case as well:
https://stackoverflow.com/a/11367508/227436