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

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();

Related

Inserting date in Mysql (codename one)

I want to insert a Date object in mysql database, which has a Date type in the database as well. I am having problems inserting the date .
I have tried this code, but it seems codename one have a problem with it:
dateString s;
s = date.getCurrentMonth() + "/" + date.getCurrentDay() + "/" + date.getCurrentYear();
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date) formatter.parse(s);
Please can you tell me how to do it ?
You don't need to format it. Just use this SQL Date Object instead of Date object from java.util package.
import java.sql.Date
// Creating a date object.
Date date = new Date();
In a database, make sure the data type of attribute 'date' is selected as "Date" also, not VarChar. Simply pass this sql package Date object into the database through query. :) It will save the date in a format.

How to take Date from sql db as a single result and compare with current date

i have a complex problem with Date field. Describe what i want to do:
I have field date1 as Date in my db.
#Temporal(TemporalType.DATE)
private Date date1;
I want to take data from this field and compare with current date.
#Query("SELECT date1 FROM Table io WHERE io.date1 >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-%e')")
Date findAll2();
public boolean CheckDate1(){
currentDate = new Date();
date1 = getInterimOrdersRepo().findAll2();
if(currentDate.before(date1) || currentDate.equals(date1)){
System.out.println("TRUE");
System.out.println("currentDate = "+currentDate);
return true;
}
else{
System.out.println("FALSE");
return false;
}
}
but i have an error:
result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException
When method return false i want do Update field data1 with " " empty data.
I using jsf, what i must to do?
It seems that you are trying to read several values from the table into a single variable, and that is the error.
findall2 returns an array (most likely) and u should read one of it's values - try reading first one.
Furthermore, I believe that you can skip the "DATE_FORMAT" in your query, and this is a very strange way to write a code. Not clear what u are trying to achieve here

Format JSON date before pushing into ko.observableArray

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.

How to deserialize date format in JSON date string?

This question someone is already asking and solution is with JavaScriptConverter (.NET) but how can I convert normal date into JSON date string with java script.
For example I have a formated date "12-12-2012" and I want to get string something like this example:
/Date(1354316400000+0100)/
Icky, awful format, and clumsy slow serializer. (IMHO)
On the server, use Json.Net and its default ISO8601 formatted dates instead.
On the client, use moment.js. It will handle all of the parsing and formatting you could want.
For posterity, if you want to output this format using moment.js, you can do one of these:
moment().format("[/Date](XSSS)/"); // /Date(1198908717056)/
moment().format("[/Date](XSSSZZ)/"); // /Date(1198908717056-0700)/
s = "12-12-2012".split("-");
epoch = Date.parse(s[2] + "-" + s[0] + "-" + s[1]);
output = "/Date(" + epoch + ")/";
if you need the timezone offset, you can use .getTimezoneOffset() on the Date Object and add that to your output string.

DateFormatting Error

I was trying to convert this format of String to Date and was unsuccessfull
"23-DEC-2008" to a Date Object ,it looks like its not accepting "-" and i could see NULL in the date object after formatting .
Can somebody let me know if u have come across this problem .
Thanks ,
Sudeep
The "-" shouldn't be an issue. I've converted SQL timestamp strings to Date objects with no problem (the format of SQL date strings is YYYY-MM-DD). What is the format string you're using? Try using the format string "DD-MMM-YYYY" and see if that works.
Edit
Sorry, my solution only applies to the DateFormatter class from Flex, and not Actionscript. After looking at the documentation for the Actionscript Date class I saw the following:
The year month and day terms can be separated by a forward slash (/) or by spaces, but never by a dash (-). (1)
If you're stuck using straight Actionscript, it looks as if you'll have to write your own parse method that accepts the "-".
this sort of works ...
public function parse(source:String):Date {
var ret:Date = new Date(0, 0, 0, 0, 0, 0, 0);
var parts:Array = source.split("-");
ret.fullYear = Number(parts[2]);
ret.setDate(Number(parts[0]));
var month:int = "jan,feb,mar,apr,may,jun,jul,aug,sep,oct,now,dec".split(",").indexOf(String(parts[1]).toLowerCase());
if (month == -1) throw "could not parse month";
ret.setMonth(month);
return ret;
}
but really, i don't like it ... if 'DEC' were 'Dec' , then
Date.parse("23-Dec-2008".split("-").join(" "))
would work ... but still ... i think, you should get something more robust ...
greetz
back2dos