Please take a look at my jsFiddle:
https://jsfiddle.net/MrSnrub/8ugu3pta/5/
Set the start date to January 9, 2012. If we look at the imported JSON feed for GOOG stock (which can be found here: https://www.highcharts.com/samples/data/jsonp.php?filename=goog-c.json), we see the following values for that range:
/* Jan 2012 */
[1325548800000,332.37], // 2012-01-03
[1325635200000,333.81], // 2012-01-04
[1325721600000,329.18], // 2012-01-05
[1325808000000,324.68], // 2012-01-06
[1326067200000,310.92], // 2012-01-09
[1326153600000,311.26], // 2012-01-10
[1326240000000,312.67], // 2012-01-11
[1326326400000,314.51], // 2012-01-12
[1326412800000,312.18], // 2012-01-13
However, my Highcharts graph says the GOOG value at 1/9/2012 is 324.68. I am fetching the seriesProcessedYData like so:
var series_processed_y_data =
e.target.series[i].processedYData;
var series_min_y_data =
series_processed_y_data[0].toFixed(2);
I am fetching the zeroth value of the array. Why is it still one day ahead, and how do I fix it?
Related
I have a [[Date:[Double]]] which I would like to sort by nearest to farthest date based on the element's key, which is a date.
What is the most efficient way to do this using Swift? I have done this before using NSSortDescriptor but this was when sorting using a key/value pair. I have not sorted by the actual key itself before.
Example data:
[[2020-12-18 06:00:00 +0000: [475.4]], [2020-11-06 06:00:00 +0000: [427.475, 449.22]], [2020-11-06 00:09:33 +0000: [435.26, 441.605]]]
As Matt suggests, make your model like this:
struct DateStruct {
let date: Date
let values: [Double]
}
var dateStructsArray: [DateStruct] = []
//Populate your array in whatever way makes sense
Then sorting it is as simple as using a single call to sorted()
Your code might look like this:
let sortedDateStructs = dateStructsArray.sorted { $0.date < $1.date }
As Duncan Suggests:
first:Parsing data what you want,
second:set data to dateStruct for a array,you can use the array to do something.
I need to set the other object's timezone to match now object which has utc timezone.
I'm comparing two datetime objects but the 'difference' value does not match the expected value. Most likely down to the fact that both objects have different Time Zones (Utc & Bst).
void main() {
var now = new DateTime.now().toUtc();
print(now);
print(now.timeZoneName);
var other = DateTime.parse("2020-05-22 18:27:32.608069");
print(other);
print(other.timeZoneName);
var diff = now.difference(other);
print(diff);
}
output:
2020-05-22 19:26:39.169Z
UTC
2020-05-22 18:27:32.608
British Summer Time
1:59:06.561000
You don't want to convert, you want to read in a date/time as UTC.
Change
var other = DateTime.parse("2020-05-22 18:27:32.608069");
to
var other = DateTime.parse("2020-05-22 18:27:32.608069z");
If other is already constructed, you need to make a new object with DateTime.utc()
https://api.dart.dev/stable/2.8.2/dart-core/DateTime/DateTime.utc.html
var newDate = new DateTime.utc(other.year, other.month, other.day, other.hour, other.minute, other.second, other.millisecond, other.microsecond);
I would like to persist the last row with yesterday's date.
My data looks like the following:
I have tried the following to persist the data, which works well.
function moveValuesOnly() {
var ss = SpreadsheetApp.getActive().getSheetByName('Store values');
Logger.log(ss.getName());
// get yesterday's date
var now = new Date();
var yesterday = new Date();
yesterday.setDate(now.getDate()-1);
yesterday = Utilities.formatDate(yesterday, "GMT+1", 'yyyy-MM-dd');
Logger.log("yesterday: " + yesterday);
var source = ss.getRange('4:4');
source.copyTo(ss.getRange('4:4'), {contentsOnly: true});
source.setFontWeight("bold");
}
Find below an example spreadsheet:
Sample Spreadsheet
As you can see I am getting yesterday's date correctly formatted in my script as in my Date column. I also can correctly 'persist' the data.
My problem is that I do not know how to get the range where yesterday's date occurs so that I can hand it over in my script to persist it.
Any suggestions how to get the row that matches yesterday's date.
not totally sure what you mean by "persist" but the function below returns the row number for the first row with yesterday's date in it:
function getYesterdayRow(yesterdayDate,columnRange) {
var displayValues = columnRange.getDisplayValues();
for (var i = 0; i < displayValues.length; i++) {
var displayValue = displayValues[i][0];
if (displayValue === yesterdayDate) return i + 1;
}
return 0;
}
You can call it like this in your code after you've defined yesterday:
var yesterdayRow = getYesterdayRow(yesterday,ss.getRange(A:A))
Note that this function quickly fixes your current need, but it uses getdisplayValues(), which is a quick cheat to not have to deal with processing the date. You should probably modify this function so that it would work with other date formats. (Use getValues(), get the day, time and month from yesterday, then the same from each value in the for loop, and make sure to account for any timezone offsets.)
I am attempting to create an array that will store 365 integers, it must be filled completely. I am using Healthkit to figure out the users steps from a year back, hence the array size. Every integer represents 1 day.
I have done this in android already and it worked perfectly, I got 365 integers back with 0's for the days with no steps, however, the problem is with iOS health kit I get nothing from days with no data, which I need. In order to do this I thought I would compare the date variable I get with the date of the current day + 1 and loop through the array to see if it find any matching cases, if not put a 0 into it at the end.
So in order to do this I created an array of 365, at the line var ID = 0 is where I attempt to store the integers correctly into the array. I am using Swift 4.
struct stepy {
static var step = [365]
}
This is where I enumerate through the stepData, first at var ID I attempt to compare the date I get in the enumerate loop with the current date (basically index 0 in the array, which represents the first day, the current day).
However I got a problem, currently I believe I would overwrite the days which already has been inputted into the date at the second step enumeration? Also I can't get the date code to compile properly, I just get the Date has no valid member called "add"
stepsQuery.initialResultsHandler = { query, results, error in
let endDate = NSDate()
let startDate = calendar.date(byAdding: .day, value: -365, to: endDate as Date, wrappingComponents: false)
if let myResults = results{
myResults.enumerateStatistics(from: startDate!, to: endDate as Date) { statistics, stop in
if let quantity = statistics.sumQuantity(){
var date = statistics.startDate
let steps = quantity.doubleValue(for: HKUnit.count())
var id = 0
var dateToInsert = date
var today = Date()
var todaytwo = Date()
for index in 0..<stepy.step.count {
if dateToInsert != today {
id = index + 1
today.(Calendar.current.date(byAdding: .day, value: -1, to: today)
stepy.step.append(0)
}
if date == dateToInsert as Date {
today.add(Calendar.current.date(byAdding: .day, value: -1, to: today)
stepy.step.append(Int(steps))
id = index + 1
}
}
}
}
}
}
static var step = [365]
The above doesn't make sense. It does not create an array of 365 integers, it creates an array with one integer in it that is 365. What you need is
static var step: [Int] = []
which creates an empty array you can just append your results to
currently I believe I would overwrite the days which already has been inputted into the date at the second step enumeration?
because your code appends to the array, which is the same as in Java: myArrayList.add(element), this is not a problem.
Also I can't get the date code to compile properly, I just get the Date has no valid member called "add"
Correct, it doesn't. Also this line:
today.(Calendar.current.date(byAdding: .day, value: -1, to: today)
does not make any sense. That should be causing a compiler error to.
Anyway, I don't see what the point of all that is. Your outer loop presumably loops through the statistics, one per day, so just do your calculation and append to the array. It'll be oldest first, but you can then just reverse the array to get newest first.
I'm working on an application that reads different health data from HealthKit application.
So far I managed to get the DOB, most recent records of height, weight and blood glucose.
What I still need is how to get the metadata for these objects, specifically I need to get the date/time the record was entered.
For example, to get the record of the height, I'm using this method:
func updateHeight()
{
// 1. Construct an HKSampleType for Height
let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
// 2. Call the method to read the most recent Height sample
self.healthManager?.readMostRecentSample(sampleType, completion: { (mostRecentHeight, error) -> Void in
if( error != nil )
{
println("Error reading height from HealthKit Store: \(error.localizedDescription)")
return;
}
var heightLocalizedString = self.kUnknownString;
self.height = mostRecentHeight as? HKQuantitySample;
// 3. Format the height to display it on the screen
if let meters = self.height?.quantity.doubleValueForUnit(HKUnit.meterUnit()) {
let heightFormatter = NSLengthFormatter()
heightFormatter.forPersonHeightUse = true;
heightLocalizedString = heightFormatter.stringFromMeters(meters);
}
// 4. Update UI. HealthKit use an internal queue. We make sure that we interact with the UI in the main thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.heightLabel.text = heightLocalizedString
});
})
}
As you notice I'm creating an HKSampleType constant then pass it to a method called readMostRecentSample which takes this parameter and then returns the most recent record for this sample type.
I tried to print line the returned object and I've got this output:
1.9 m "Health" metadata: { HKWasUserEntered = 1; } 2015-05-17 10:11:00 +0300 2015-05-17 10:11:00 +0300
As you see the output includes the metadata of the object, but actually I couldn't extract only the date.
Also I found that there is a property of the object called metadata, I printed it out but it only retrieved me a boolean of whether the data was entered by the user (manually) or automatically from a third party:
println(self.height?.metadata)
The output was:
[HKWasUserEntered = 1]
I would be grateful and thankful if someone can give me any idea of how to extract the metadata of each object.
A HKSample object and its subclasses like HKQuantitySample have 2 fields that store date information : startDate and endDate. If you are trying to get the date this is where you should look.
Some samples—for example, body temperature—represent a single point in
time. For these samples, both the start and the end date are the same,
because they both refer to the point in time when the sample was
taken.
Other samples—for example, step count—represent data over a time
interval. Here, the sample should use different start and end dates.
These dates mark the beginning and end of the sample’s time interval,
respectively.
From the documentation https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HKSample_Class/index.html#//apple_ref/occ/instp/HKSample/startDate