I have a problem with dates manipulation with Ionic and moment.js.
I store some dates from a ion-datetime component :
{"year":2017,"month":7,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0}
And use moment.js to "humanize" date display :
let somedate = moment(some.date);
console.log('JSON date : ' + JSON.stringify(some.date) + ' resolved as : ' + somedate.format('DD/MM/YYYY'));
And got result :
Original JSON date : {"year":2017,"month":7,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0} resolved as : 26/08/2017
As you can consider, there's on month offset between original JSON date and moment display date...
What i'm missing ?
The Javascript month are in range of 0-11 i.e. January is 0, February is 1 and likewise, therefore it is moving you to the next month. Try subtracting 1 from month value, to get the correct month.
var some = {'date':{"year":2017,"month":6,"day":26,"hour":null,"minute":null,"second":null,"millisecond":null,"tzOffset":0} };
let somedate = moment(some.date);
console.log('JSON date : ' + JSON.stringify(some.date) + ' resolved as : ' + somedate.format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Finally, with your answers, i resolved the problem with a conversion method that take the original JSON date format and return a Javascript Date object, using TypeScript :
private _JSONDateToDate(jsonDate: any){
if(typeof jsonDate == 'object')
return new Date(jsonDate.year, (parseInt(jsonDate.month) - 1), jsonDate.day);
return jsonDate;
}
I substract 1 month of the "month" property in order to have a correct Date object... then, i can manipulate it with moment.js
Related
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();
Is it possible to pass a piped date as an argument for a function?
I am thinking of something along the lines of...
A variable date: string that will be assigned a value passed from a datepicker
The date picker currently outputs date values in the format:
Fri Feb 09 2018 00:00:00 GMT+0000 (GMT Standard Time)
It is possible to display the date in binding with use of date | date:'yyyy-MM-dd'
I am wanting to pass into a function, that piped date - something like:
someFunction(date | date:'yyyy-MM-dd');
Is there any way that this could be possible?
Or will I have to pass the original long date into a function, mutate it and then use it?
I have since found a way to just JS it - How do I get a date in YYYY-MM-DD format?
This splits the date and then recombines it into a string:
onSelect(theDate: Date): void {
var yyyy = theDate.getFullYear().toString();
var mm = (theDate.getMonth()+1).toString();
var dd = theDate.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
var dateString = yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
this.meetingService.getMeetingsByDate(dateString);
}
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.
I am using grails.
After render object as json, here what i got :
result : {"temp {"class":"com.mine.domain.Guest","id":32,"address":"","city":"",
"country":null,"customerType": {"class":"CustomerType","id":1},
**"dob":"1984-07-10T16:00:00Z"**.......
How to reformat dob to dd/mm/yyyy in jquery?
Thanks.
the jQuery dateTimePicker will do the job http://xdsoft.net/jqplugins/datetimepicker/
var datestringToDate = function(datestring){
var myDate = datestring.substr(0,10).split("-");
return myDate[2] + '/' + myDate[1] + '/' + myDate[0];
}
datestringToDate("1984-07-10T16:00:00Z"); will return "10/07/1984"
If you decide to use this, you also got to make sure that the dates come in always in the same format ("YYYY-MM-DDTGIBBERISH"), since it's just a simple string parser and nothing else.
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.