How to convert string to time? - javascript

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

Related

Sorting and filtering on Date

I have a date column and need to be able to both sort and filter on it. The data comes in as strings like 2010-12-23 and can pre-processed as needed. It should be shown as 23.12.2010. Some internationalization will come later.
I wonder what's the proper internal representation:
a string like "23.12.2010" is bad for sorting (it could be done by sorting on function result, but it'd be slow)
a string like "2010-12-23" sorts correctly, can be formatted easily, but filtering for 23.12 does not work (it could be done, but it'd be slow)
Date would probably get sorted correctly, but filtering would be slow
moment could be the solution, no idea
My current idea is to create an object containing both milliseconds and the displayed string, so that all operations can be fast. But I'd bet that someone was that smart before me....
Let's assume that showing dates in the form like 2010-12-23 is unacceptable, otherwise the problem is solved. To summarize, the problem is that I need to
display and filter in the DD.MM.YYYY format
sort according to the numerical value (or equivalently, as if it was in th ISO format).
I think the method you're proposing wouldn't run in to too many performance issues, unless you're going for really old browsers or mobile devices.
I've mocked up an example to do a quick (performance) test. First, I'm defining an object that holds a value optimized for sorting, and a value optimized for display:
var MyDate = function(dateString) {
var date = new Date(dateString);
var displayValue = "{0}.{1}.{2}"
.replace("{0}", prefixZeroIfNeeded(date.getUTCDate()))
.replace("{1}", prefixZeroIfNeeded(date.getUTCMonth() + 1))
.replace("{2}", date.getUTCFullYear());
return {
sortKey: date.getTime(),
displayValue: displayValue
};
};
The prefixZeroIfNeeded method ensures we get the DD.MM format rather than the dd.mm one:
var prefixZeroIfNeeded = function(nr) {
return nr < 10 ? "0" + nr : "" + nr;
};
Then, we need some data to convert:
var data = [];
var myDates = data
.map(MyDate)
.sort(function(date1, date2) {
return date1.sortKey - date2.sortKey;
});
Finally, a quick example of a very basic search function:
var searchMyDates = function(str) {
return myDates.filter(function(myDate) {
return myDate.displayValue.indexOf(str) !== -1;
});
};
Now, we can create some mockup data and check how long it would actually take to A) map and sort the raw strings to the MyDate objects, and B) search for a string in our collection.
Here's how I generated the raw data:
for (var i = 0; i < 10000; i += 1) {
var y = Math.floor(Math.random() * 101) + 1900;
var m = prefixZeroIfNeeded(Math.floor(Math.random() * 13));
var d = prefixZeroIfNeeded(Math.floor(Math.random() * 29));
data.push(y + "-" + d + "-" + m);
}
Using console.time to measure, processing the data on my machine (A) takes around 40ms. Searching for the string .12. takes around 5-10ms.
Concluding: I think you were definitely on the right track and could continue work in the proposed direction. However, in my personal experience, I've learned that whenever I start work on a feature that involves dates and times, moment.js is the way to go. You'll eventually run in to daylight saving time, time zones, you name it and regret you thought it was simple...
Let me know if this is of any help.
Edit: the code in a snippet (check your browser console for output)
var data = [];
var prefixZeroIfNeeded = function(nr) {
return nr < 10 ? "0" + nr : "" + nr;
};
// Generate random data:
for (var i = 0; i < 10000; i += 1) {
var y = Math.floor(Math.random() * 101) + 1900;
var m = prefixZeroIfNeeded(Math.floor(Math.random() * 13));
var d = prefixZeroIfNeeded(Math.floor(Math.random() * 29));
data.push(y + "-" + d + "-" + m);
}
var MyDate = function(dateString) {
var date = new Date(dateString);
var displayValue = "{0}.{1}.{2}"
.replace("{0}", prefixZeroIfNeeded(date.getUTCDate()))
.replace("{1}", prefixZeroIfNeeded(date.getUTCMonth() + 1))
.replace("{2}", date.getUTCFullYear());
return {
sortKey: date.getTime(),
displayValue: displayValue
};
};
console.time("Map and sorting");
var myDates = data
.map(MyDate)
.sort(function(date1, date2) {
return date1.sortKey - date2.sortKey;
});
var searchMyDates = function(str) {
return myDates.filter(function(myDate) {
return myDate.displayValue.indexOf(str) !== -1;
});
};
console.timeEnd("Map and sorting");
console.time("Search");
console.log("Searching for the month 12, %d results.", searchMyDates(".12.").length);
console.timeEnd("Search");
This may help you a bit. I have used the same thing working with React. Here is a link for Moment.js -
http://momentjs.com/docs/#/displaying/format/
If you go under Display -> Format on the right menu bar, you'll see localized formats, you will need to use format L - pre defined format from moment which will show you 09/04/1986 (September 4, 1986); otherwise you can create your own using DD-MM-YYYY format.
For Example, The way I used in React for my exercise is
To define a variable using let:
let deadlineFormated = Moment(this.props.ToDoItem.deadline).format('llll');
Hope this helps for Angular!
Gist: Decouple sorting and filtering. Do sorting on the internal representation and filtering on the presentation.
Sort on internal representation that is in any naturally sortable format. Your raw YYYY-MM-DD date strings would work, so would parsing them into Date objects. The performance difference could be negligible unless you're dealing with lots and lots of rows -- but in that case you would already have other issues with latency and rendering performance.
It's more intuitive if free-text filtering is done on what's displayed (the presentation). So if you're formatting the dates as "May 7, 2016", do a substring match on that. If you're formatting the dates as DD.MM.YYYY, do a substring match on that.
If filtering is driven by actual date selections from controls like a date picker or a select field, you can do the filtering on the internal representation.
Try with this:
Get Unixtimestamp for date (i.e. Numeric format) and use jquery sort.
Please check this example for jquery sort. Regarding example replace your unixtimestamp to value.
<ul id="datelist">
<li value="1360013296">Date 1</li>
<li value="1360013297">Date 2</li>
<li value="1360013298">Date 3</li>
<li value="1360013299">Date 4</li>
</ul>
https://jsfiddle.net/ajaygokhale/bohgoq8o/
To reliably implement sorting converting it into a Date Object is recommended (new Date(str))
If you need to be flexible in formatting moment has formatting support (check moment.format()) as well. Moment has pretty deep locale support as well.
You can always keep it a Date Object as the source of truth and for filtering you could do Date.toString() just at the time of filtering. This returns a string you could then filter with.

How to customize JSON output on the first level ONLY using JavaScript's stringify() method?

I use stringify() method in JavaScript to convert a list of objects to a string, but I need to customize the output on the first level ONLY like the following:
[
/*T01*/ {"startX":55,"endX":109,"sartY":0,"endY":249},
/*T02*/ {"startX":110,"endX":164,"sartY":0,"endY":249},
/*T03*/ {"startX":165,"endX":219,"sartY":0,"endY":249},
/*T04*/ {"startX":220,"endX":274,"sartY":0,"endY":249},
/*T05*/ {"startX":275,"endX":329,"sartY":0,"endY":249},
/*T06*/ {"startX":330,"endX":384,"sartY":0,"endY":249},
/*T07*/ {"startX":385,"endX":439,"sartY":0,"endY":249},
/*T08*/ {"startX":440,"endX":494,"sartY":0,"endY":249},
/*T09*/ {"startX":495,"endX":549,"sartY":0,"endY":249},
/*T10*/ {"startX":550,"endX":604,"sartY":0,"endY":249}
]
Now there are other parameters in stringfy() method, replacer and space, can't I use them to format my output like the aforementioned format including:
tabs
spaces
comments
You are not going to get JSON.parse to make that output since it is not valid JSON. But if you want to have something rendered like that, it is a simple loop and string concatenation.
var details = [
{"startX":55,"endX":109,"sartY":0,"endY":249},
{"startX":110,"endX":164,"sartY":0,"endY":249},
{"startX":165,"endX":219,"sartY":0,"endY":249},
{"startX":220,"endX":274,"sartY":0,"endY":249},
{"startX":275,"endX":329,"sartY":0,"endY":249},
{"startX":330,"endX":384,"sartY":0,"endY":249},
{"startX":385,"endX":439,"sartY":0,"endY":249},
{"startX":440,"endX":494,"sartY":0,"endY":249},
{"startX":495,"endX":549,"sartY":0,"endY":249},
{"startX":550,"endX":604,"sartY":0,"endY":249}
];
var out = "[\n" + details.map(function(val, i) {
var id = "\t/*T" + ("0" + (i + 1)).substr(-2) + "*/\t";
return id + JSON.stringify(val);
}).join(",\n") + "\n]";
console.log(out);

Convert Date in to custom format in javascript

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.

Format Date in Javascript/JQuery as Single Digit Day

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.

ISO duration with Java script

I apologize for the question because I have already posted a similar question, but I would like to know how I can do the following conversion:
PT11H9M38.7876754S
I want to disable seconds and only show hour and minutes 11:09
When I have time displays minutes from 1 to 9, I want to add a 0 in front of number
Tnx in advice...
You could try this:
var str = 'PT11H9M38.7876754S'
match = str.match(/(\d*)H(\d*)M/),
formatted = match[1] + ':' + (!match[2][1] ? 0 + match[2] : match[2]);
console.log(formatted); // => 11:09
"PT11H9M38.78767545".replace(/PT(\d+)H(\d+)M.*/,function(m,a,b) {return a+":"+(b.length<2?"0":"")+b;});
One-liner :p
Since all the nice RegExp stuff is above here is a third solution a bit more expensive in terms of parsing but you may be looking for something different.
You can use the split function to parse the string and extract the portions that you need.
var pt="PT11H9M38.7876754S";
function showtime(s){
var time = s.split('.');
var hours = time[0].split('T')[1].split('H')[0];
var minutes = time[0].split('H')[1].split('M')[0];
return digitize(hours) + ":" + digitize(minutes)
}
function digitize(i){
return (i>9) ? i : "0" + i;
}
alert(showtime(pt)); // 11:09

Categories