Google Datastore -> Compare DateTime-Property with Date - datetime

I just can't find an answer to the following problem:
I have entities in my Google App Engine Datastore which all have a property of the type "Date and time". My Datastore console shows me the format of that property. It looks like this:
2/16/16, 7:20 PM CET
Now I want to do a query that only gives back the entities AFTER a specific date. But how do I format that date? I tried the following:
#ApiMethod(name = "getUpdatedEpisodes", path = "getUpdatedEpisodes")
public List<Episode> getUpdatedEpisodes(#Named("lastUpdate") String lastUpdate) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy, hh:mm a z");
Date date = null;
try{
date = sdf.parse(lastUpdate);
}catch (Exception ex){
}
Query.Filter filter =
new Query.FilterPredicate("lastUpdate",
Query.FilterOperator.GREATER_THAN,
date);
Query q = new Query("Episode").setFilter(filter);
PreparedQuery pq = datastore.prepare(q);
Afterwards I try to set a new date and run this method again. I do the following:
repository.getInstance(context).lastUpdate = DateTime.now(DateTimeZone.forID("CET")).toString("dd/MM/yy, hh:mm a z");
While debugging I can see that this String looks like
2/16/16, 7:24 nachm. GMT+01:00
And if I try my API with this string again, I will still get all my episodes, so no filtering was done. Is this because my Date and the Google Date can't be compared if they aren't the exact same format? How can I fix this?

Rather than using a String for your date property, you can use a Date object:
import java.util.Date;
...
repository.getInstance(context).lastUpdate = new Date();
The Datastore will store this property so that it is sorted in chronological (or anti-chronological) order and query filters will work as expected.
https://cloud.google.com/appengine/docs/java/datastore/entities#Java_Properties_and_value_types

I solved this issue by storing my date in the datastore as millis instead of date and time. This way I only have an 64-bit integer that is easy to compare.

Related

Comparing two datetime

I send a datetime using query $post to Mvc Controller;
1- On the server machine it doesn't bind well , some time in wrong format
I solved it by sending datetime as string then split the string to day, month , year.
2- Second problem; I parsed the datetime but when I compare it with another one it gives me wrong result.
Post your date/time formatted in the ISO standard.
var myDate = new Date();
var dateString = myDate.toISOString();
Post dateString to your api.

Determine Time Offset given Olson TZID and local DateTime?

I need to determine Time Offset given Olson TZID of an event and a DateTime of an event.
I suppose I can do it with a help of Noda Time, but I'm new here and need help - an example of actual API call sequence to perform this task.
A few more details of what we're using and doing.
We're running ASP.NET + SQL Server based Web site. Users of our site enter and save events which are happening at various locations. For each event Lat/Long and DateTime with time offset (of that event) are among required fields.
There are various scenarios of data entry, sometimes Lat/Long is entered first, sometimes DateTime is. System allows to determine Lat/Long from an address or a map point. We want Time Offset to be consistent with Lat/Long in most of the cases because we normally expect DateTime being entered as local to that event.
We use SQL Server DateTimeOffset field to store data.
We don't want to depend on third-party web services to determine an offset, but prefer our system to do that.
I'm free to download and use any necessary tools or data. I already downloaded shapefiles from http://efele.net/maps/tz/ and used Shape2SQL http://goo.gl/u7AUy to convert them to SQL Server table with TZIDs and GEOMs.
I know how to get TZID from Lat/Long by querying that table.
What I need, again, is to determine Time Offset from TZID and DateTime.
Thank you for Jon Skeet and Matt Johnson for providing an answer on Noda Time Google Group http://goo.gl/I9unm0. Jon explained how to get Microsoft BCL DateTimeOffset value given Olson TZID and NodaTime LocalDateTime values. Matt pointed to an example of determining if DST is active given ZonedDateTime: What is the System.TimeZoneInfo.IsDaylightSavingTime equivalent in NodaTime?
I'm going to write a blog post summarizing my experience of getting Olson TZID from Lat/Long, parsing DateTime string into LocalDateTime and determining DateTimeOffset. I'll show there how GetTmzIdByLocation(latitude, longitude) and GetRoughDateTimeOffsetByLocation(latitude, longitude) methods work and why I needed both (first method doesn't work for locations on ocean). Once I write this post I'll add a comment here.
Note, that parsing DateTime string in a code below is not optimal yet; as Matt explained in a Google Group post (link above) it's better to use Noda Time tools than BCL. See a related question at http://goo.gl/ZRZ7XP
My current code:
public object GetDateTimeOffset(string latitude, string longitude, string dateTime)
{
var tzFound = false;
var isDST = false;
var tmpDateTime = new DateTimeOffset(DateTime.Now).DateTime;
if (!String.IsNullOrEmpty(dateTime))
{
try
{
// Note: Looks stupid? I need to throw away TimeZone Offset specified in dateTime string (if any).
// Funny thing is that calling DateTime.Parse(dateTime) would automatically modify DateTime for its value in a system timezone.
tmpDateTime = DateTimeOffset.Parse(dateTime).DateTime;
}
catch (Exception) { }
}
try
{
var tmzID = GetTmzIdByLocation(latitude, longitude);
DateTimeOffset result;
if (String.IsNullOrEmpty(tmzID) || tmzID.ToLower() == "uninhabited") // TimeZone is unknown, it's probably an ocean, so we would just return time offest based on Lat/Long.
{
var offset = GetRoughDateTimeOffsetByLocation(latitude, longitude);
result = new DateTimeOffset(tmpDateTime, TimeSpan.FromMinutes(offset * 60)); // This only works correctly if tmpDateTime.Kind = Unspecified, see http://goo.gl/at3Vba
} // A known TimeZone is found, we can adjust for DST using Noda Time calls below.
else
{
tzFound = true;
// This was provided by Jon Skeet
var localDateTime = LocalDateTime.FromDateTime(tmpDateTime); // See Noda Time docs at http://goo.gl/XseiSa
var dateTimeZone = DateTimeZoneProviders.Tzdb[tmzID];
var zonedDateTime = localDateTime.InZoneLeniently(dateTimeZone); // See Noda Time docs at http://goo.gl/AqE8Qo
result = zonedDateTime.ToDateTimeOffset(); // BCL DateTimeOffset
isDST = zonedDateTime.IsDaylightSavingsTime();
}
return new { result = result.ToString(IncidentDateFormat), tzFound, isDST };
}
catch (Exception ex)
{
IMAPLog.LogEvent(System.Reflection.MethodBase.GetCurrentMethod().Name, "", ex);
throw new CustomHttpException("Unable to get timezone offset.");
}
}
An extension method (provided by Matt Johnson) for determining if DST is active What is the System.TimeZoneInfo.IsDaylightSavingTime equivalent in NodaTime?
public static class NodaTimeUtil
{
// An extension method by Matt Johnson - on Stack Overflow at http://goo.gl/ymy7Wb
public static bool IsDaylightSavingsTime(this ZonedDateTime zonedDateTime)
{
var instant = zonedDateTime.ToInstant();
var zoneInterval = zonedDateTime.Zone.GetZoneInterval(instant);
return zoneInterval.Savings != Offset.Zero;
}
}

JSON date to asp.net DateTime is changed at runtime

I've searched around and I'm really not sure why this happens.
Most of the time my app runs in GMT from devices using GMT, but I just span a server up in Singapore, so the time is 8hrs ahead. I'm seeing some strange behaviour with DateTime objects parsed from JSON:
My app received a JSON (ISO 8601) date like this:
LastSync=2013-01-10T11:05:38.822Z
I'm using a simple .asmx web-service, that uses the built in JSON serializer for .Net 3.5, the automatically parsed DateTime object returns a date 8hrs ahead of what the JSON says it should be. Here's the function:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function SyncFlatTable(ByVal tableName As String, ByVal LastSync As DateTime)
Return WebServiceJSON.SyncFlatTable(tableName, LastSync)
End Function
As you can see the LastSync as DateTime argument's value is 8hrs ahead:
The weird thing is if I return Now(), the JSON output from the web service is:
newLastSend=/Date(1357817197087)/
Which using a timestamp to date online converter is no-longer 8hrs ahead.
Is this IIS's fault? I can't see any other culture settings everything else is neutral, why would it change the date? How do I stop it, or do I have to take what I'm given and adjust the date to an invariant culture date?
I got this problem as well, I ended up using the sting type to pass in/out the date info.
It seems that calling .toJSON on any date object, when it's converted to a string representation it is done so using a local date. I needed to adjust this to UTC so that when it's converted it does so with what the date should be for the server:
function removeDateUTCOffSetForServer(obj) {
if (obj) {
for (prop in obj) {
if (obj[prop] instanceof Date) {
var d = obj[prop];
var utc = new Date(d.getTime() - (d.getTimezoneOffset() * 60000));
obj[prop] = utc;
}
}
}
return obj;
}

showing DateTime in simple format?

i have a column in my database that stores DateTime, now i want to show time in simple format,
you know it will appear like : 12/26/2011 9:39:55 PM
but i want to show it in persian.
When you want to format the DateTime in your application, you need to use a DateTime.ToString overload.
Select the appropriate standard Date and Time format string - in this case "g" looks like a good fit.
If you have not set up your webserver to use the fa-IR culture by default, you will need to pass this culture in as well.
string farsiDate = myDateTime.ToString("g", CultureInfo.GetCultureInfo("fa-IR");
Have a look at the examples on MSDN for using the PersianCalendar class.
var cal = new PersianCalendar();
var today = DateTime.Now;
var persianDate = string.Format("{0}/{1}/{2}",
cal.GetDayOfMonth(today),
cal.GetMonth(today),
cal.GetYear(today));

How to pass a Date object from Flex to a JSP Servlet?

I am passing some parameters as POST to a Servlet from my Flex WebApplication. I am able to pass and retrieve strings properly.
I used new Date().getTime() in my flex code and tried passing the timestamp variable hoping to parse it at the servlet and convertit into a java.util.Date object. But i am getting a NumberFormatException when i try to parse the variable from the string that i got from request.getParameter.
Any solutions?
I think you are not converting String to long in Java IF so Please try
String strDateinmilliseconds = request.getAttribute("FlexMilliseconds");
long dateinmilliseconds = Long.valueOf(strDateinmilliseconds);
Date resultdate = new Date(dateinmilliseconds);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
System.out.println(sdf.format(resultdate));
Hopes that helps

Resources