I have a Date format like this
2014-11-18T20:50:01.462Z
I need to convert to the custom format like "20:50 2014-18-11" using Javascript date function
I need result like
20:50 2014-18-11
How to get this , Thanks in Advance :)
Assuming you're able to include new libraries on your project, I'd highly recommend moment.js (MIT license) instead of writing this yourself. It solves problems like zero padding etc. for you.
Example
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<script>
// Use an existing date object
var date = new Date("2014-11-18T20:50:01.462Z");
console.log(moment(date).format('HH:mm YYYY-DD-MM'));
// or use string directly
console.log(moment.utc("2014-11-18T20:50:01.462Z").format('HH:mm YYYY-DD-MM'));
</script>
Note by default moment will use your current timezone for output, this can be overridden using the zone() function
console.log(moment.utc("2014-11-18T20:50:01.462Z").zone(0).format('HH:mm YYYY-DD-MM'));
console.log(moment.utc("2014-11-18T20:50:01.462Z").zone('UTC+05:30').format('HH:mm YYYY-DD-MM'));
Output
20:50 2014-18-11
Try moment js its very nice plugin to play around dates and times
so all you need to do is import moment js and put this line in your js code
using moment.js will also help you in future for your code
moment.utc("2014-11-18T20:50:01.462Z").format("HH:mm YYYY-DD-MM")
Use this Demo JsFiddler
var d = new Date,
dformat = [ d.getHours().padLeft(), d.getMinutes().padLeft()].join(':')
+ ' ' +
[d.getFullYear(), d.getDate().padLeft(), (d.getMonth()+1).padLeft()].join('-')
;
Date.prototype._padding = function(v, w) {
var f = "0000" + v;
return ("0000" + v).substr(f.length-w, f.length)
}
Date.prototype.MyDateString = function() {
return this._padding(this.getUTCHours(), 2) + ":" + this._padding(this.getUTCMinutes(), 2) + " " + this.getUTCFullYear() + "-" + this._padding(this.getUTCDate(), 2) + "-" + this._padding((this.getUTCMonth() + 1), 2);
}
console.log(new Date('2014-11-18T20:50:01.462Z').MyDateString())
console.log(new Date('2014-11-08T02:05:01.462Z').MyDateString())
getUTCMonth return 10, as the month is 0 based.
Related
Currently, I'm parsing a JSON which returns a string like this for time "201610161000"(2016-10-16 10:00). I used Momentjs to parse it like this "moment("201610161000", 'YYYYMMDDHHmm')" The problem is that it takes too much time when I parse it with large data. If I remove it, then it only takes 10ms. Otherwise, it takes 1000 ms with Momentjs. Is there a way that I can convert the string above to time without using Moment? (I have no control to change the time format in JSON)
var inner = _.map(num.series, function(n, k) {
return {
x: moment(n.bucket, 'YYYYMMDDHHmm'),
y: n,
};
});
This can be done using concatenation and split methods in java-script.
Try following approach
var jsonTime = "201610161000".split("");
var parsedDate = jsonTime.slice(0, 4).join("") + "-" + jsonTime.slice(4, 6).join("")+ "-" + jsonTime.slice(6, 8).join("")+ "-" + jsonTime.slice(8, 10).join("")+ ":" + jsonTime.slice(10, 12).join("");
//output : 2016-10-16-10:00
I'm using the ag-grid component in my code and would like to ensure that date columns are formatted according to the customers needs when exported as CSV. A default format for a js Date object is used currently. The code can be found here:
https://github.com/ceolter/ag-grid/blob/master/src/ts/csvCreator.ts
I could make the following change to the code directly, but this is obviously bad practice. I'm fairly new to JavaScript and was wondering if there is a standard way to extend/override functionality in a library like this.
Proposed change (Note this shows the change I made to the js version not the github version which uses ts):
--- Common/scripts/agGrid/ag-grid.js (revision b0e7d54e61e6371b0cab94428cb4329f9f62db11)
+++ Common/scripts/agGrid/ag-grid.js (revision )
## -1848,7 +1848,11 ##
+ var exportDateAs = function(dt){if (dt instanceof Date)
+ return dt.getFullYear() + "/" + (dt.getMonth()+1) + "/" + dt.getDate();
+ };
## -1883,6 +1887,9 ##
+ if (valueForCell instanceof Date){
+ valueForCell = exportDateAs(valueForCell);
+ }
It looks like this functionality was added in a newer version:
https://www.ag-grid.com/javascript-grid-export/
My solution was to update the function in the ag grid component manually as follows. It appears to work, but not sure if it is best practice. Anyone willing to comment?
Replace function in object with my own:
ag.grid.CsvCreator.prototype.getDataAsCsv = agCustom.getDataAsCsv;
New function
var agCustom;
(function (agCustom) {
// This is a modified version of the getDataAsCsv from
// agGrid to allow date formatting in csv export
agCustom.getDataAsCsv = function (params) {
var LINE_SEPARATOR = '\r\n';
...
var exportDateAs = function(dt){if (dt instanceof Date)
return dt.getFullYear() + "/" + (dt.getMonth()+1) + "/" + dt.getDate();
...
else {
valueForCell = _this.valueService.getValue(column.colDef, node.data, node);
if (valueForCell instanceof Date){
valueForCell = exportDateAs(valueForCell);
}
...
})(agCustom || (agCustom = {}));
How can I convert a python timestamp with javacript
from 2014-07-28T20:45:04.271935
to 1.6.2014 (20:45)
I tried to use the builtin parse function from javascript, but it seems to mix up things..
out = new Date(context);
out = out.getDay() + ". " + out.getMonth() + ". " + out.getFullYear() + " (" + out.getHours()+ ":" + out.getMinutes() + ")";
If you work with date and time intensively in your application I'd recommend you to use Moment.js library for painless conversions:
moment('2014-07-28T20:45:04.271935').format('D.M.YYYY (H:m)');
// Will return "28.7.2014 (20:45)"
moment('2014-07-09T20:45:04.271935').format('DD.MM.YYYY (H:m)');
// Will return "09.07.2014 (20:45)"
And if you need to format the date and time only in one place then just build the string manually as you did in your code example.
Currently, I am pulling in a json feed from our calendar. It brings back the date in the yyyy/mm/dd format... I know I can overwrite this format by using javascript but how would I do this? I need the output to only be the "dd" not the month nor the year.
I would also like single digit days to show up as i.e. "1","2","3","4" and of course dbl digits to show up as usual "10", "11", "12", etc. Any ideas on how I could achieve this reformatting of the date via javascript/jquery?
You can use a Date object
var theDate = new Date(dateString);
var theDay = parseInt(theDate.getDate(), 10);
Alternatively, if you don't want to use the object and can expect the same string back each time:
var theDay = parseInt(dateString.split('/')[2], 10);
This code should do it . . .
var jsonDate = <...reference to the JSON date value...>;
var dayValue = jsonDate.split("/")[2].replace(/0(.)/, "$1");
You've already got a string value, so might as well just manipulate it as a string.
jsonDate.split("/")[2] splits up the full date and then takes the third item from the resulting array (i.e., the day value)
.replace(/^0(.)$/, "$1") will trim off the "0", if it finds it in the first position of the "day" string
Then you just use dayValue wherever you need to use it. :)
UPDATE:
Based on the comments below, try using this as your code:
var listingEl = $('<div class="eventListings" title="' + item.event.title + '" />');
var dateEl = $('<div class="mdate">' + dayValue + '</div>');
var linkEl = $('<a href="' + item.event.localist_url + '" />');
var titleEl = $('<div class="mcTitle">' + item.event.title + '</div>');
linkEl.append(titleEl);
listingEl.append(dateEl);
listingEl.append(linkEl);
$('#localistTitle').append(listingEl);
UPDATE 2:
There was something not working in your code (I think the main issues was how you were using .appendTo()). I split it out into a multi-step process and used .append() instead. It worked correctly when I tested it locally.
If I have a date like 8/9/2010 in a textbox, how can I easiest set a variable to the value 201098?
Thanks in advance.
var date = "8/9/2010";
var result = date.split('/').reverse().join('');
EXAMPLE: http://jsfiddle.net/hX357/
To add leading zeros to the month and day (when needed) you could do this:
var date = "8/9/2010";
var result = date.split('/');
for( var i = 2; i--; )
result[i] = ("0" + result[i]).slice(-2);
result = result.reverse().join('');
EXAMPLE: http://jsfiddle.net/hX357/2/
I would recommend using Datejs to process your dates.
You can do something like
date.toString("yyyyMMdd");
to get the date in the format you want
Using regex:
"8/9/2010".replace(/([0-9]+)\/([0-9]+)\/([0-9]+)/,"$3$2$1")
Do a split on '/', take the last element and make it the first of a new string, the middle element becomes the middle element of the new string, and the first element becomes the last element of a new string.
It would be like this:
myString = document.getElementById('date_textbox').value;
var mySplitResult = myString.split("\");
var newString = mySplitResult[2] + mySplitResult[1] + mySplitResult[0];
This is basically the idea I think you are going for.
-Brian J. Stinar-
Dang, it looks like I was beaten to the punch...
Or you can use the built-in JavaScript Date class:
function processDate(dStr) {
var d = new Date(dStr);
return d.getFullYear() + (d.getMonth() + 1) + d.getDate();
}
processDate("8/9/2010");
Easiest to manage and debug, certainly.