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
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 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.
In my code, I have this:
<script language="javascript">
function addNumbers()
{
var collect = parseFloat(document.getElementById("Collect").value);
var current = parseFloat(document.getElementById("Current").value);
var Balance = document.getElementById("Bal");
Balance.value = collect + current;
}
</script>
If, for example,the input is: 123.12 + 12.22, the Balance is 135.34
But if the input is : 123.00 + 12.00, the Balance is 135 instead of 135.00.
What should I add to achieve the 2nd output sample?
Thanks.
Use ToFixed(2) mdn
(123.00 + 12.00).toFixed(2) //135.00
Also , use || operator.
So :
function addNumbers()
{
var collect = parseFloat(document.getElementById("Collect").value) ||0;
var current = parseFloat(document.getElementById("Current").value) ||0;
var Balance = document.getElementById("Bal");
Balance.value = (collect + current).toFixed(2);
}
Small gotcha :
(9.999 +9.999).toFixed(2) //"20.00"
So how would I solve it ?
simply :
Multiply by 1000 each and then move decimal point.
It sounds like parseFloat() is working correctly but it's the output that isn't quite to your liking. Try using Number's .toFixed() function for formatting:
Balance.value = (collect + current).toFixed(2)
There's some great discussions of formatting currency over on this question: How can I format numbers as money in JavaScript?
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.
I have this as my date: 1212009 so this should be like 12/1/2009 but I am stuck this as an id field and id fields cannot have dashes in there names.
Now can java-script take this number and re add the slashed in for me or how would I go about doing this?
Thanks
You should have two-digit numbers for the month and day, since "1212009" is ambiguous, could be interpreted as "1/21/2009" or "12/1/2009".
If you add the leading zeros, you know that there will be always 8 digits, so you can do something like this:
var str = "12012009"
var result = str.replace(/(\d{2})(\d{2})(\d{4})/, "$1/$2/$3");
// 12/01/2009
Or
var result = str.match(/(\d{2})(\d{2})(\d{4})/).slice(1).join('/');
// 12/01/2009
Well without leading zeros, it's not possible to make a reliable conversion. It's impossible to know if 1232009 is 1/23/2009 or 12/3/2009 without leading zeros. Also, your example number could be interpreted as 1/21/2009 too.
All you need to do is pass the string into the new date constructor.
Here is a good javascript resource for you to look at.
http://www.javascriptkit.com/jsref/date.shtml
Assuming that you add the leading zeroes to remove the ambiguity, you can format the date like so:
dateString = String(id).match(/(\d{2})(\d{2})(\d{4})/).slice(1).join('/')
Maybe this will help you to get rid of the six or seven numbers long date (most important part is the first part):
var sDate = "1212009";
if(sDate.length == 7){
sDate = sDate.substr(0,2) + "0" + sDate.substr(2);
}
else if(sDate.length == 6){
sDate = "0" + sDate.substr(0,1) + "0" + sDate.substr(1);
}
// This part can be done with Regular Expressions, as shown in other comments
var month = parseInt(sDate.substring(0,2));
var day = parseInt(sDate.substring(2,4));
var year = parseInt(sDate.substring(4));
alert(day + "/" + month + "/" year);
// Will alert 12/1/2009
However,
1232009 will always be 01/23/2009, not 12/03/2009
112009 changes to 1/1/2009
10102009 changes to 10/10/2009