How can specify time location for CreatedAt when selecting results? - timezone

I have a table with CreatedAt fild as "timestamp with timezone"
when I select rows I have entities with CreatedAt with time zone in my location, and I want to have it as UTC.
type app struct {
ID uuid.UUID
CreatedAt time.Time
}
db, err := gorm.Open(
postgres.Open(databaseURL),
&gorm.Config{},
)
if err != nil {
panic(err)
}
a := &app{}
db.Table("applications").Take(a)
fmt.Println(a.CreatedAt)
it prints "2023-02-01 11:26:29.554589 +0300 MSK"
and I would like to have "2023-02-01 08:26:29.554589 +0000 UTC"
Is there some option for that (gorm-v2)?
gorm-v1 retrieves as UTC, by the way. And gorm-v2 - in current location

I am not sure why you are using timestamp with timezone, but here are a few solutions to this issue. The solution I found useful (see here) is to provide a NowFunc when connecting to the database:
db, err := gorm.Open(postgres.Open(connectionString), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
NowFunc: func() time.Time {
utc, _ := time.LoadLocation("")
return time.Now().In(utc)
},
})
Then you can see that your data is saved according to your table specifications and it is displayed as you expected in Go.

Related

Flutter/Dart DateTime parsing UTC and converting to local

I am trying to parse a UTC Date string to DateTime and then parse it to local, however I am having troubles with converting it to the local time. In the UK it should be plus one, however when I print .isUtc it returns as false.
This is what I have now:
print(widget.asset.purchaseDate);
DateTime temp = DateTime.parse(widget.asset.purchaseDate);
print(temp.toLocal());
I/flutter (5434): 2020-05-07 21:29:00
I/flutter (5434): 2020-05-07 21:29:00.000
You need to indicate a timezone to DateTime.parse, otherwise it assumes local time. From the dartdoc:
An optional time-zone offset part, possibly separated from the
previous by a space. The time zone is either 'z' or 'Z', or it is a
signed two digit hour part and an optional two digit minute part.
Since you know your string represents UTC, you can tell the parser by adding the Z suffix.
var temp = DateTime.parse(widget.asset.purchaseDate + 'Z');
print(temp.isUtc); // prints true
While #Richard Heap's answer stands I'd like DateTime.parseUtc() to exist.
If there will be a day when dart allows static extension methods here is an implementation that would work:
extension DateTimeExtension on DateTime {
static DateTime parseUtc(String formattedDate) => DateTime.parse('${formattedDate}z');
static DateTime? tryParseUtc(String? formattedDate) {
if (formattedDate != null) {
return DateTime.tryParse('${formattedDate}z');
}
return null;
}
}
Currently you'd have to use it with the extension classes name, like so:
DateTimeExtension.parseUtc(someDate)
or
DateTimeExtension.tryParseUtc(someOtherDate)
I think the latter is more useful where someOtherDate is nullable

Check if pointer object created is less than today Parse.com

hey guys i have a table A which has a pointer to Table B. I am trying to query Table A where Table B created At is less than today
Table A (columns)
objectId, Name, Table B pointer, ....
Table B
objectId, EndDate
So far I have this
let query = PFQuery(className:Globals.ParseObjects.ProLeagueWinnings)
query.fromLocalDatastore()
query.fromPinWithName("XXX")
query.includeKey("TableB")
query.whereKeyExists("TableB")
query.whereKey("TableB.EndDate", lessThanOrEqualTo: NSDate())
query.findObjectsInBackground().continueWithSuccessBlock {
(task: BFTask!) -> AnyObject! in
let leagues = task.result as? [ProLeagueWinnings]
if (completion != nil){
if leagues != nil{
completion!(leagues!)
}else{
completion!([])
}
}
return task
}
But it returns everything.
Instead of using EndDate, you could always use the createdAt attribute that is automatically created for you by Parse.
It is also important to remember that NSDate() will return the current absolute time including the hours, minutes and so on. So you will be getting all objects in the relationship (being pointed to) that were created before the exact instant of execution.
See: How to get current date at midnight

How to get metadata from HealthKit?

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

Golang XML Unmarshal and time.Time fields

I have XML data I am retrieving via a REST API that I am unmarshal-ing into a GO struct. One of the fields is a date field, however the date format returned by the API does not match the default time.Time parse format and thus the unmarshal fails.
Is there any way to specify to the unmarshal function which date format to use in the time.Time parsing? I'd like to use properly defined types and using a string to hold a datetime field feels wrong.
Sample struct:
type Transaction struct {
Id int64 `xml:"sequencenumber"`
ReferenceNumber string `xml:"ourref"`
Description string `xml:"description"`
Type string `xml:"type"`
CustomerID string `xml:"namecode"`
DateEntered time.Time `xml:"enterdate"` //this is the field in question
Gross float64 `xml:"gross"`
Container TransactionDetailContainer `xml:"subfile"`
}
The date format returned is "yyyymmdd".
I had the same problem.
time.Time doesn't satisfy the xml.Unmarshaler interface. And you can not specify a date fomat.
If you don't want to handle the parsing afterward and you prefer to let the xml.encoding do it, one solution is to create a struct with an anonymous time.Time field and implement your own UnmarshalXML with your custom date format.
type Transaction struct {
//...
DateEntered customTime `xml:"enterdate"` // use your own type that satisfies UnmarshalXML
//...
}
type customTime struct {
time.Time
}
func (c *customTime) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
const shortForm = "20060102" // yyyymmdd date format
var v string
d.DecodeElement(&v, &start)
parse, err := time.Parse(shortForm, v)
if err != nil {
return err
}
*c = customTime{parse}
return nil
}
If your XML element uses an attribut as a date, you have to implement UnmarshalXMLAttr the same way.
See http://play.golang.org/p/EFXZNsjE4a
From what I have read the encoding/xml has some known issues that have been put off until a later date...
To get around this issue, instead of using the type time.Time use string and handle the parsing afterwards.
I had quite a bit of trouble getting time.Parse to work with dates in the following format: "Fri, 09 Aug 2013 19:39:39 GMT"
Oddly enough I found that "net/http" has a ParseTime function that takes a string that worked perfectly...
http://golang.org/pkg/net/http/#ParseTime
I've implemented a xml dateTime format conforming a spec, you can find it on GitHub: https://github.com/datainq/xml-date-time
You can find XML dateTime in W3C spec
A niche technique to override the JSON marshaling/unmarshaling of select keys in a struct is also applicable to XML marshaling/unmarshaling, with minimal modifications. The idea remains the same: Alias the original struct to hide the Unmarshal method, and embed the alias in another struct where individual fields may be overridden to allow the default unmarshaling method to apply.
In your example, following the idea above, I'd do it like this:
type TransactionA Transaction
type TransactionS struct {
*TransactionA
DateEntered string `xml:"enterdate"`
}
func (t *Transaction) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
const shortForm = "20060102" // yyyymmdd date format
var s = &TransactionS{TransactionA: (*TransactionA)(t)}
d.DecodeElement(s, &start)
t.DateEntered, _ = time.Parse(shortForm, s.DateEntered)
return nil
}
The smartest point of this method is, by sending TransactionS into DecodeElement, all fields of t gets populated through the embedded alias type *TransactionA, except for those overridden in the S-type. You can then process overridden struct members as you wish.
This approach scales very well if you have multiple fields of different types that you want to handle in a custom way, plus the benefit that you don't introduce an otherwise useless customType that you have to convert over and over again.
const shortForm = "20060102" // yyyymmdd date format
It is unreadable. But it is right in Go. You can read the source in http://golang.org/src/time/format.go

How to order by time and time only in C#?

I have this recorded in SQL Server:
1- startTime (datetime): 5/2/2009 08:30 (brazilian time format: d/m/y)
2- startTime (datetime): 4/2/2009 14:30 (brazilian time format: d/m/y)
My application just records time... the date it's SQL that generates by itself be getting the date of today.
When I ask VS 2008 to order this datetime fields, it returns me that code #2 is before #1, because 4/2/2009 comes before 5/2/2009.
But, actually I want it to order by time only and ignore the date.
Is it possible??
Thanks!!
André
from d in dates
orderby d.TimeOfDay
select d;
or
dates.OrderBy(d => d.TimeOfDay);
Note: This will work as long as this is plain LINQ and not LINQ-to-SQL. If you're using LINQ-to-SQL to query your database, you'll need something that will translate to SQL.
You might also try fixing your app so it always saves the same base date with the time (like '01/01/1900' or whatever) and then you do not have to do all these slow and inefficient date stripping operations every time you need to do a query.
Or as Joel said, truncate or strip off the date portion before you do the insert or update.
Well, you can't really store a datetime without a date, but you could just store the total seconds as an double (using #florian's method).
You'd have to add a second method to convert this back to a date in your object, if you still need a date, such as:
public class BusinessObjectWithDate
{
private string _someOtherDbField = "";
private double _timeInMS = 0; // save this to the database
// sort by this? in sql or in code. You don't really need this
// property, since TimeWithDate actually saves the _timeInMS field
public double TimeInMS {
get { return _timeInMS; }
}
public DateTime TimeWithDate { // sort by this too, if you want
get { return (new DateTime(1900,1,1).AddMilliseconds(_timeInMS)); }
set { _timeInMS = value.TimeOfDay.TotalMilliseconds; }
}
}
var f = new BusinessObjectWithDate();
MessageBox.Show( f.TimeWithDate.ToString() ); // 1/1/1900 12:00:00 AM
f.TimeWithDate = DateTime.Now;
MessageBox.Show( f.TimeWithDate.ToString() ); // 1/1/1900 1:14:57 PM
You could also just store the real date time, but always overwrite with 1/1/1900 when the value gets set. This would also work in sql
public class BusinessObjectWithDate
{
private DateTime _msStoredInDate;
public DateTime TimeWithDate
{
get { return _msStoredInDate; }
set {
var ms = value.TimeOfDay.TotalMilliseconds;
_msStoredInDate = (new DateTime(1900, 1, 1).AddMilliseconds(ms));
}
}
}
Try this in your sql:
ORDER BY startTime - CAST(FLOOR(CAST(startTime AS Float)) AS DateTime)

Resources