Format JSON date before pushing into ko.observableArray - json

I am pushing Values into a ko.observalbeArray with an AJAX call,
I want to format the JSON return date to "YYYY-MM-DD" before I am pushing it into my observableArray.
The Specific element in my Code that I want to convert is: OrderTimeStamp: element.OrderTimeStamp
Here is an example of a date that gets returned from server:
/Date(1377200468203+0200)/
Here is my AJAX call:
$.ajax({
url: "/[URL TO API Method]/GetAllOrdersbyparm",
data: {Parm: ko.toJS(MyDataViewModel.SelectedParmater), Start: ko.toJS(MyDataViewModel.ParmStart), End: ko.toJS(MyDataViewModel.ParmEnd)},
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
for (var i = 0; i < Result.d.length; i++) {
element = Result.d[i];
MyDataViewModel.OrderDetails.push({ OrderID: element.OrderID, OrderGUID: element.OrderGUID, OrderTimeStamp: element.OrderTimeStamp, OrderStatus: element.OrderStatus, QtyProductsOnOrder: element.QtyProductOnOrder, PaymentDate: element.PaymentDate });
}
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});

So, this is an ASP.NET specific Microsoft Date "standard".
See
http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx
why it should be avoided like the plague(1).
In that format the first component is a UTC milliseconds offset since the UNIX epoch.
The offset is TO local time, which is the opposite of the timezone offset in the JS Date string representations.
Use
var dateString = myDate.toJSON();
to serialize a JS Date object for sending.
Such a serialized datetime string, which is also in UTC (aka *Z*ulu), can be used to create a Date object thusly:
var myDate = new Date(dateString);
(1) In case you need to support this old ASP.NET Date format you can convert it to a proper JS Date like this (thanks [Roy Tinker][2]):
myDate = new Date(parseInt("/Date(1377200468203+0200)/".substr(6)));
I'm not familiar with that particular datetime notation.
Is that home-grown?
Is there documentation for that?
If not, then you are setting yourself up for trouble trying to interpret it.
That conversion toJSON would make it a UTC time and a few things are open for interpretation, unless documented in minute (no pun intended) detail.
So this is my answer: Be very sure you have the above definition in normative writing.
Now let me ramble on for a bit:
I went through that little exercise here...
http://en.wikipedia.org/wiki/ISO_8601 would be a good standard to base datetime notation on.
Now, you already get that format from the server, which looks like a millisecond time value since the epoch ('1970-01-01T00:00:00Z'), (probably with a timezone offset already applied to it!) combined with a timezone offset string in HHMM.
That's a bit scary, since those two components don't mix well.
Evaluated as an expression 1377200468203+0200 would subtract octal! 200 milliseconds! from 1377200468203. That's clearly not what's intended.
In ISO8601 (which this notation is not) this timezone offset would be FROM UTC, so the millisecond value would already have the 2 hour, 0 minutes offset applied to it.
Now the code could of course run on a machine which is in a different timezone than the datetime given.
The very crucial question is whether this millisecond datetime value has indeed the offset FROM UTC in it.
In that case, doing
var dt = new Date(1377200468203);
would be wrong.
If it is close to a daylight savings time switch time, it would be incorrect to just subtract to offset from it.

Note, not sure if below answers your question. If not, you may be helped by this one: How to format a JSON date?
Something along these lines should work:
var yyyy = element.OrderTimeStamp.getFullYear()
var mm = element.OrderTimeStamp.getMonth();
var dd = element.OrderTimeStamp.getDate();
var x = yyyy + '-' + (mm < 10 ? '0'+mm : mm) + '-' + (dd < 10 ? '0'+dd : dd)
element.OrderTimeStamp = x;
See this fiddle for an example. For reference, the MDN page has good documenation on Dates.
If you need more advanced date and time functionality I can recommend looking at MomentJS.

Related

How to format abd get empty time with it with moment when it doesn't exist in string?

I have a use case where I have variable data in the following formats. When the string doesn't have time, the format object formats it with 12:00:00 => 12:00 am.
Well technically, the constructor that passes only a date IS instantiating it with a time, 12:00:00, even though it is implicit.
Example
'2021-02-12'
'2021-02-12T6:00'
'2021-02-19T18:00'
Code
const date = moment("2021-02-12");
date.format("h:mm a"); // 12:00 am
Expected
I'd like to know if that is possible that moment format the time with the empty string "" when time is not available in the data. e.g.
const date = moment("2021-02-12");
date.format("h:mm a"); // ""

Dates are incorrect with json passed like "jsonObject.toString()"

I have a graph component written in javascript using the canvas. You can update its values if you pass it a valid json array, of dates, coupled with prices of that date (stock trading candlesticks).
The jsonArray I try to populate on this call usually comes from creating new dates in js - but is there a way to send my jsonArray down the wire (from Primefaces) in such a way that the dates get interpreted as dates?
When I use
PrimeFaces.current().executeScript("myFunction(" + jsonObject.toString() + ")");
Dates that come down the wire are becoming long looking numbers which I guess are the number of milliseconds since 1970. What can I do to send this (rather large) jsonarray and have its dates interpreted as dates? (they fail on the date.getMonth() call, because they are numbers instead of dates).
When creating the jsonArray on the server side, I do the following, which looks wrong because getTime() returns a long. So how would dates be properly handled here?
json.addProperty("date", data.getKey().getTs().getTime());
The function getting called with the long values as dates was the following. As Ultimater suggested, pass this object through new Date() - which should work for a date object - as well as a long, so no harm done!
dateToString(date, multiline) {
if(date === null)
return;
// Added this
date = new Date(date);
var datestr = date.getMonth() + " " + date.getDay() + ", " + date.getFullYear();

Milliseconds to DateTime in WP8 not working

I need to convert a date in milliseconds to a user readable date and I can't.
My date is: 1494519599999 which corresponds to: Thu May 11 2017 18:19:59 GMT+0200
I need to get something like dd/mm/yyyy HH:mm:ss
I have tried what I read in other stackoverflow posts:
DateTime date = new DateTime(long.Parse(ticks));
date.ToString("yyyy-MM-ddThh:mm:ssZ");
But I always get 0 for year, month and more. I tought I should multiply or divide by 1000 the number but it was worst.
What is the correct way to do this?
The timestamp seems to be the value often used in JavaScript to represent a date (the number of milliseconds elapsed since January 1 1970). You can convert that to a DateTimeOffset using this code:
var timestamp = 1494519599999;
var epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero);
var dateTimeOffset = epoch.AddMilliseconds(timestamp);
The result is 05/11/2017 16:19:59 +00:00.
I am using a DateTimeOffset to make it easier for you to change the offset from +0000 to +0200. You can change the offset using this code where I assume you want to convert to local date and time. Windows Phone 8 does not support the full functionality of the TimeZoneInfo class so if you need to convert to another time zone you need create code the explicitely changes the offset:
dateTimeOffset = dateTimeOffset.ToLocalTime();
Now the result is 05/11/2017 18:19:59 +02:00.
If you prefer to use DateTime instead of DateTimeOffset you can use this code to create a UTC DateTime:
var timestamp = 1494519599999;
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var dateTime = epoch.AddMilliseconds(timestamp);
The result is 05/11/2017 16:19:59 and if your local timezone has a offset of +0200 you can convert it to a local DateTime to get the desired result. However, when time zones are involved I suggest that you use DateTimeOffset.
Try this:
var time = TimeSpan.FromMilliseconds(milliseconds);

Sequelize query with dates

I'd like to make a query on dates using SequelizeJS but i don't know how to do and there is nothing on that on the website...
My code :
var day = request.params.day;
Appointment.findAll({where: ["start.day() = day"]}); // start is my column, format with DATETIME
Depending on your DB there might be some function to extract the day from the column. Never seen the .day syntax before though.
Appointment.findAll({
where: sequelize.where(sequelize.fn('day', sequelize.col('start')), day)
});
On latest master this should produce something like
WHERE DAY("start") = day
You can just use the regular comparison operator, as long as your date is in a valid format. For this purpose you can just create a Date object out of the input, and then pass it to the Sequelize query, like this:
var day = new Date(request.params.day);
Appointment.findAll({where: ['start > ?', day]}).then(function (result) {
// do stuff here
});

DateField: selectedDate shows hours as 24:00:00

With a DateField component, the selectedDate.getHours returns as 24:00:00. I want it to return as 00:00:00.
Is there an easy way to do this?
Thanks!
UPDATE:
First, I set a variable in my Model that equals the selectedDate of a DateField component:
model.generalInfo.endDate = endDate_df.selectedDate;
Then I set another variable based on that value and I trace it out:
param.todate = df.format( model.generalInfo.endDate.toString() );
And this is where I see the time equal to 24:00:00
you could try something like
selectedDate.time = selectedDate.time - 24 * 60 * 60 * 60 * 1000
as a Date.time represents miliseconds since 1970 or whatever.. you substract 24 hours..
if it not works for you, you can create a new function or getter that converts it, or you can create a new mxml module, with DateField as superclass, and you can override the getHours method. tons of options to do this..
It looks like you are using the Flex DateFormatter to format the Date object. Have a look at the docs for this class, it has a formatString property that you can use to control how to output the date (or in this case the time).
If you give the DateFormatter a format string that contains "H" will output the hour in 24 hour format using the number range 1-24. If the format string contains "J" it will output the hour in 24 hour format using the range 0-23.
To get your desired output, use "JJ" in the format string, in addition to any other items. For example to output the hours, minutes, seconds:
var someDate:Date = new Date(2012, 11, 5);
var df:DateFormatter = new DateFormatter();
df.formatString = "JJ:NN:SS";
var formatted:String = df.format(someDate); // 00:00:00
Also, as #Flextras mentioned, there is Flash localization API you can use which has the added benefit of converting date/time strings to the values used by their locale. These are the DateTimeFormatter classes:
fl.globalization.DateTimeFormatter
spark.formatters.DateTimeFormatter (Flex 4)
These classes format dates into the user's locale (or one that you specifcy), and format Date objects the same way the DateFormatter does.