With libary moment there is option to bring a array of formating options and momentjs use the best match for parsing the input.
For Example:
var date = moment("29-06-1995", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]);
but what if I want the take the same format that using in parsing for output formating.
var dateText = date.format('selected parse')
How do I know which format moment choose to use?
Currently there is no exposed function for getting the chosen format, however there is a "private" field named _f that contains this information.
var m = moment("29-06-1995", ["MM-DD-YYYY", "DD-MM", "DD-MM-YYYY"]);
m._f // "DD-MM-YYYY"
If you use this, be careful when updating versions of moment. Private fields are not guaranteed to be maintained, and could break between versions.
I've logged this as a feature request for future moment.js functionality.
Related
Sorry about the bad title, I didn't exactly know how to phrase that any better. I'm going to try to explain what I need as best as possible.
I'm currently making a Task Manager (a ToDo list) in Javascript where you can create tasks, set a schedule for them and then you would have a list with all the tasks that you need to do and the respective schedule of each task (beginning and ending date).
I'm using Angular.js and Angular Material to do my UI. I have the Angular Material's datepicker. This is the code I use to get the date value:
angular.module('KBTM_App', ['ngMaterial']).controller('AppCtrl', function($scope) {
$scope.myDate1 = new Date();
...
// This is where I get the date value
var initial_date_1 = angular.element(document.querySelector('[ng-controller="AppCtrl"]')).scope().myDate1;
The problem is that this datepicker is returning the date in this format:"2016-04-29T08:36:10.027Z", which I don't want. I want a more normal format, like "DD-MM-YYYY".
I tried converting the date format with Moment.js, but that didn't work. Here's the code I used for that:
var initial_date = moment(initial_date_1, "YYYY-MM-DD'T'HH:MM:SS.SSS'Z'").format("DD-MM-YYYY");
And then I would store that date in the localStorage:
// Get the other dates already in the list
var initial_dates = get_initial_dates();
// Adds the new date to that list
initial_dates.push(initial_date);
// Stores those dates in the localStorage
localStorage.setItem('initial_date_db', JSON.stringify(initial_dates));
With that code I get "Invalid date" when trying to add a new task to the task list.
Sorry for the long post!
Thanks to whoever can help me.
You can convert the date format in html using angular material datepicker by using following code.
data-ng-value="myDate1 | date : 'shortDate'"
Use the angular date filter to format the date. Refer the link angular date
var initial_date = $filter('date')($scope.myDate1, "dd-MM-yyyy");
Inject the $filter in your controller main module.
Best way to handle dates is to use momentjs and there is a special AJS Directive available. angular-moment
You can check [momentjs][2] offical docs for detailed info. You have to add angular-moment as dependency injection to use moment easily. https://github.com/urish/angular-moment#instructions-for-using-moment-timezone-with-webpack
I am using Node.js to query MongoDB and have a field that is a Date (ISODate). In Node.js after querying the Date format that is returned looks like this
DT : 2014-10-02T02:36:23.354Z
What I am trying to figure out is how based on the code i have below, can efficiently convert the DT field from UTC to Local Time ISOString. In other words if local time is EDT then something like this
DT : 2014-10-02T23:36:23.354Z
I don't think there is anything I can do in the query itself from Mongo. Should I traverse the Array result set and manually change the dates? Is there a better approach here? I am sending the response to an HTTP client.
collection.find(query,options).toArray(function (err, items) {
if (err) {
logAndSendDebugError(500, "Error issuing find against mongo Employees Collection -" + type, res);
} else {
var response = {
'type': type,
'employees': items
};
res.jsonp(response);
}
});
In ES5, Date.parse should be able to parse that format, however it isn't reliable. Manually parsing it isn't hard:
// Parse ISO 8601 UTC string like 2014-10-02T23:36:23.354Z
function parseISOUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]));
}
The date instance that is created will have a local timezone offset calculated from system settings. To get a UTC ISO 8601 string from a local date you can use toISOString:
var date = new Date();
console.log(date.toISOString());
Note that toISOString is ES5 so may need a polyfill if this is used in older browsers. See MDN Date.prototype.toISOString().
I would have thought the most efficient way to handle dates between the client and server would be to use the EJSON package. This covers a few things that are skirted around in other discussion here and the importance is placed on maintaining "type fidelity" when handling JSON conversion.
So what you are getting right now is the result of a "string" which is called from the "Date" object in response to a JSON.stringify call. Whatever the method being used, this is essentially what is happening where the .toJSON() method is being called from the "Date" prototype.
Rather than muck around with the prototypes or other manual processing of coversions, the EJSON package allows you to call EJSON.stringify instead which has some built in behavior to preserve types, where specifically the generated JSON string would look like this for a Date element:
{ "myCreatedDate": { "$date": 1412227831060 } }
The value there is an epoch timestamp, essentially obtained from the .valueOf() prototype method, but the field is given a special structure automagically as it were. The same is true for types other than dates as well.
The corresponding "client" processing which you can add with simple includes to your web application in the browser, e.g:
<script src="components/ejson/base64.js"></script>
<script src="components/ejson/ejson.js"></script>
This allows a same EJSON object to be present where you can process the received JSON with EJSON.parse. The resulting JavaScript Object is maintained as a "Date" type when the de-serialize is done.
var obj = EJSON.parse( "{ \"myCreatedDate\": { \"$date\": 1412227831060 } }" );
{
myCreatedDate: /* Actually a Date Object here */
}
So now in your client browser, you have a real Date object without any other processing. Any .toString() method called on that object is going to result in a value represented in a way that matches the current locale settings for that client.
So if you use this to pass the values around between server and client in a way that is going to maintain an actual "Date" object, then the correct Object values are maintained on either client and server and needs no further conversion.
Very simple to include in your project and it takes a lot of the heavy lifting of maintaining "timezone" conversions off your hands. Give it a try.
Probably worth noting that the "core" of this comes from a MongoDB specification for Extended JSON Syntax. So aside from this (partial) implementation in the EJSON package, the same "type identifiers" are supported in several MongoDB tools as well as within several driver implementations with a custom JSON parser that will automatically convert the types. Notably the Java and C# drivers have this capability shipped with the driver libraries.
It's fairly easy to follow the convention outlined in that link, and it is intended to "map" to the BSON type specifications as well. At the worst, you can always "inspect" the results from a standard JSON parser and implement custom routines to "re-instantiate" the "types". But as noted, the software is already in place with several libraries.
I have searched for this but couldn't find anyone trying to do what i am doing with jqGrid formatters.
I have a date which I am trying to parse which is not in a jqGrid table, but I am using jqGrid on the site elsewhere and am hoping to parse this date using jqGrid's date parser instead of having to write a seperate method.
I have been messing around with the jGrid object but I need a little help with this.
My date format is ISO8601Long i.e. 2013-11-17T09:00:00
First, I am ensuring the date formats in the formatter are the ones i wish to use:
jQuery.jgrid.formatter.date.srcformat = 'Y-m-d H:i:s';
jQuery.jgrid.formatter.date.newformat = 'j/m/Y g.ia';
Next, I call the jQuery.jgrid.parseDate method in an attempt to parse the date.
jQuery.jgrid.parseDate(0, 0, '2013-11-17T09:00:00');
I am not sure what the first two arguments are, but they look like they might accept a srcformat and newformat. Either way, they don't format as I would expect. There is a fourth too, but this seems to only accept an object.
This leaves me with 2013-11-17GMT09:00:00. While this is a bit easier to understand, it is not in the format I would be expecting. I presume I have missed a step or somehow need to call the formatter after this.
Any pointers would be great.
Thanks,
Dale
The correct usage of parseDate would be the following:
var parsedData = $.jgrid.parseDate("Y-m-d H:i:s", "2013-11-17T09:00:00", "j/m/Y g.ia");
or
var parsedData = $.jgrid.parseDate("ISO8601Long", "2013-11-17T09:00:00", "j/m/Y g.ia");
You can use alternatively Globalize jQuery Plugin.
I am trying to use the date.format and getting an error that format is not a recognized method. I tried to use thesame in new solution, and I'm getting a correct result. Any idea why .format method is not working? These both are in Javascript.
Assuming you are talking about Date type...
It is clear why format method is not working - because there is no such method on Date object.
It is less clear why/when it would work - most likely you are using some script library that modifies Date object to have format method.
But if you are talking about some other type - format function may be present (or added) to any object and it is not possible to suggest anything without code...
I.e. custom object with format function:
var date = { format:function() {alert("Hi");}};
date.format();
I'm trying to convert an HTML table to Excel in Javascript using new ActiveXObject("Excel.application"). Bascially I loop through table cells and insert the value to the corresponding cell in excel:
//for each table cell
oSheet.Cells(x,y).value = cell.innerText;
The problem is that when the cell is in date format of 'dd-mm-yyyy' (e.g. 10-09-2008), excel would read as 'mm-dd-yyyy' (i.e. 09 Oct 2008). I tried to specify NumberFormat like:
oSheet.Cells(x,y).NumberFormat = 'dd-mm-yyyy';
But, it has no effect. It seems that this only affect how excel display the value, not parse. My only solution now is to swap the date like:
var txt = cell.innerText;
if(/^(\d\d)-(\d\d)-\d\d\d\d$/.test(txt)) txt = txt.replace(/^(\d\d)-(\d\d)/,'$2-$1');
But, I'm worrying that it is not generic and a differnt machine setting would fail this.
Is there a way to specific how excel parse the input value?
You can avoid Excel's date parsing by entering the data using its native 'serial' date format. e.g '22nd Dec 08' is 39804 as an Excel serial date. (See here for a good explanation of these)
Then format the cell as you did before.
determine what culture-neutral date formats excel supports
use javascript to parse your date string and output in the an appropriate format
I don't know what formats excel supports but you'd want something like .net's round trip or sortable formats, where it will always be read consistently.
for #2, if you can trust javascript to construct an appropriate date from whatever string you feed it that's fine. if you're not sure about that you might look at a library like datejs where you can be more specific about what you want to happen.
Instead of
oSheet.Cells(x,y).NumberFormat = 'dd-mm-yyyy';
set this:
oSheet.Cells(x,y).NumberFormat = 14;
In Vbscript, we use to resolve this by
If IsDate ( Cell.Value ) Then
Cell.Value = DateValue ( Cell.Value )
End If
Maybe, In java script also you need to play with same approach.
I've tried your code but at end of the process, I re-applied format to the columns containing dates. It works fine, no matter what local language you have configurated yor machine.
Being my excel object defined as 'template', as soon as I got it data filled, I applied (just for example):
template.ActiveSheet.Range("D10:F99").NumberFormat = "dd/MMM/yyyy;#";
best regards