convert digit into string in javascript - javascript

I have a number which represent time and I need to convert this number into string.
Like n = 800 , it represent time = 8:00
Currently I am doing this:
n = 800;
string time = '' + n/100 + ' : ' + n % 100 ;
but time become 8 : 0 but I want to minutes in two digit format like 8 : 00
Anybody please help me there?

var n = 800;
var hours = Math.floor(n/100);
var minutes = ('0' + (n%100)).slice(-2);
var time = hours + ':' + minutes;
Note the rounding on hours as well, otherwise you could end up with something like "8.56:56".

If all you are trying to do here is insert a colon before the last two digits you can just do a string replace:
var time = ("" + n).replace(/(\d\d)$/,":$1");
Or slice out the hours and minutes and concatenate with a colon:
var time = "" + n;
time = time.slice(0,-2) + ":" + time.slice(-2);

Just a shortcut solution :P
var a = 800;
var b = a.toString();
var first = b.replace(b.substring(b.length - 2),":"+b.substring(b.length - 2));
http://jsfiddle.net/6pfhyhhg/

Related

How To parse timeString with different Locales?

I want to split a time string in an with hours minutes and ampm seperately.
When I tried it for English time strung with below code :
var time = "3:20 PM";
var patternParsed = time.replace(new RegExp("(\\W", "g")," ").split(" ");
o/p for patternParsed is 3,20,PM
but similar i want to do for korean time string
When I try the above regular expression for korean time string it does not works
var koreanTime = new Date().toLocaleTimeString('ko-KR');
document.writeln("\nKoreanTime : "+koreanTime);
var patternParsed = koreanTime.replace(new RegExp("(\\W", "g")," ").split(" ");
document.writeln("\nparsed pattern : "+patternParsed);
Can someone please help me with this hiw can I split timeString of different locales?
To get a standardized output of hours,minutes,[AM|PM] considering the locale adds an unnecessary complexity, it you already have the Date object, you can use it to generate the value:
var time = new Date();
if (time.getHours() < 12) {
var patternParsed = time.getHours() + "," + time.getMinutes() + ",AM";
} else {
var patternParsed = (time.getHours() - 12) + "," + time.getMinutes() + ",PM";
}
var koreanTime = time.toLocaleTimeString('ko-KR');
document.writeln("\nKoreanTime : " + koreanTime + "\nparsed pattern : " + patternParsed);

how to convert the minutes into hours and minutes with subtracted time(subtracted time values)

I want to subtract the two different 24 hours time format.
I had tried with following :
var startingTimeValue = 04:40;
var endTimeValue = 00:55;
var hour = startingTimeValue.split(":");
var hour1 = endTimeValue.split(":");
var th = 1 * hour[0] - 1 * hour1[0];
var tm = 1 * hour[1] - 1 * hour1[1];
var time = th+":"+tm;
This code is working fine if second minutes is not greater than the first.but other case it will return minus values.
The above code sample values result :
time1 : 04:40
time2 : 00:55
The result should be : 03:45 (h:mi) format.
But right now I am getting 04:-5 with minus value.
I had tried with the link as : subtract minutes from calculated time javascript but this is not working with 00:00 format.
So how to calculate the result value and convert into hours and minutes?
I would try something like the following.
The way I see it, it is always better to break it down to a common unit and then do simple math.
function diffHours (h1, h2) {
/* Converts "hh:mm" format to a total in minutes */
function toMinutes (hh) {
hh = hh.split(':');
return (parseInt(hh[0], 10) * 60) + parseInt(hh[1], 10);
}
/* Converts total in minutes to "hh:mm" format */
function toText (m) {
var minutes = m % 60;
var hours = Math.floor(m / 60);
minutes = (minutes < 10 ? '0' : '') + minutes;
hours = (hours < 10 ? '0' : '') + hours;
return hours + ':' + minutes;
}
h1 = toMinutes(h1);
h2 = toMinutes(h2);
var diff = h2 - h1;
return toText(diff);
}
Try:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
var subtractedValue = time1 - time2;
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
DEMO
This solution utilizes javascript built-in date. How it works:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
time1, time2 is the number of miliseconds since 01/01/1970 00:00:00 UTC.
var subtractedValue = time1 - time2;
subtractedValue is the difference in miliseconds.
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
These lines reconstruct a date object to get hours and minutes.
This works better , A fiddle I just found
var difference = Math.abs(toSeconds(a) - toSeconds(b));
fiddle
This method may work for you:
function timeDiff(s,e){
var startTime = new Date("1/1/1900 " + s);
var endTime = new Date("1/1/1900 " + e);
var diff = startTime - endTime;
var result = new Date(diff);
var h = result.getUTCHours();
var m = result.getUTCMinutes();
return (h<=9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m);
}
var startingTimeValue = "04:40";
var endTimeValue = "00:55";
var formattedDifference = timeDiff(startingTimeValue,endTimeValue);
Demo: http://jsfiddle.net/zRVSg/

Javascript: Adding digits without Sum?

I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:
var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.
Any Suggestions?
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
edit:
To account for zero-padding you can do something like:
function format(x){
if (x < 10) return '0' + x;
return x;
}
var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
Convert the numerical value to a string:
var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();
If you want it to always be 6 characters long, you need to pad the values if they are < 10. For example:
var hours = date.getUTCHours();
if (hours < 10)
hours = '0' + hours.toString();
else hours = hours.toString();
var mins = date.getUTCMinutes();
if (mins < 10)
mins = '0' + mins.toString();
else mins = mins.toString();
var secs = date.getUTCSeconds();
if (secs < 10)
secs = '0' + secs.toString();
else secs = secs.toString();
var time = hours + mins + secs;
That's happening because those functions return an Integer type. If you want to add the digits themself togheter, try converting every variable to string using toString()

JavaScript unixtime problem

I get the time from the database in Unix format.
It looks like this: console.log (time);
Result: 1300709088000
Now I want to reformat it and pick out only the time, I found this: Convert a Unix timestamp to time in JavaScript
That did not work as I want. The time I get is this:
1300709088000
9:0:0
1300709252000
6:33:20
1300709316000
0:20:0
1300709358000
12:0:0
1300709530000
11:46:40
It is very wrong times when I know that times are quite different. How can I fix it?
console.log(time);
var date = new Date(time*1000);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes + ':' + seconds;
console.log(formattedTime);
It looks like this: console.log (time); Result: 1300709088000
That doesn't look like a Unix timestamp (seconds since The Epoch), it looks like milliseconds since The Epoch. So you wouldn't multiply by 1000 to convert from seconds to milliseconds for JavaScript, it's already in milliseconds (or you're dealing with dates more than 41,000 years from now; which is fair enough).
Test:
var times = [
1300709088000,
1300709252000,
1300709316000,
1300709358000,
1300709530000
];
var index;
for (index = 0; index < times.length; ++index) {
display(times[index] + " => " + new Date(times[index]));
}
Live copy
Update: Or getting the individual parts:
var times = [
1300709088000,
1300709252000,
1300709316000,
1300709358000,
1300709530000
];
var index, dt;
for (index = 0; index < times.length; ++index) {
dt = new Date(times[index]);
display(times[index] +
" => " +
dt +
" (" + formatISOLikeDate(dt) + ")");
}
// Not all implementations have ISO-8601 stuff yet, do it manually
function formatISOLikeDate(dt) {
var day = String(dt.getDate()),
month = String(dt.getMonth() + 1), // Starts at 0
year = String(dt.getFullYear()),
hour = String(dt.getHours()),
minute = String(dt.getMinutes()),
second = String(dt.getSeconds());
return zeroPad(year, 4) + "-" +
zeroPad(month, 2) + "-" +
zeroPad(day, 2) + " " +
zeroPad(hour, 2) + ":" +
zeroPad(minute, 2) + ":" +
zeroPad(second, 2);
}
function zeroPad(str, width) {
while (str.length < width) {
str = "0" + str;
}
return str;
}
Live copy ...but if you're going to be doing much of anything with dates, I'd look at DateJS.
Your time stamps are not in Unix format, they're already in the Javascript millisecond resolution format.
Hence you shouldn't be multiplying by 1000 when you create your Date object.
I've tried to do something like this:
console.log (time);
where date = new Date (time);
/ / hours party from the timestamp
was hours = date.getHours ();
/ / party minutes from the timestamp
Every minute = date.getMinutes ();
/ / Seconds Party From The timestamp
where seconds = date.getSeconds ();
/ / Will display time up 10:30:23 format
was formattedTime = hours + ':' + minutes + ':' + seconds;
console.log (formattedTime);
The result is this:
1300709088000
NaN: NaN: NaN

dynamically create table with time increments

I need to create a table with just 1 column containing times (starting from 4hrs) which increase in increments of 10 seconds for each row. So it needs to look something like this:
04hrs 00mins 00secs - 04hrs 00mins 09secs
04hrs 00mins 10secs - 04hrs 00mins 19secs
04hrs 00mins 20secs - 04hrs 00mins 29secs
.....
06hrs 59mins 50secs - 06hrs 59mins 59secs
This will obviously take a long long time to hard code so I'm looking to create it dynamically. Based on what i'm currently trying to learn I'd like to be able to do this using jquery or asp.net (vb) but anything will do as long as it works!
Thanks
Basic date-time arithmetic.
// format the given date in desired format
// ignores date portion; adds leading zeros to hour, minute and second
function fd(d){
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
return (h < 10 ? '0'+h : h) + 'hrs ' +
(m < 10 ? '0'+m : m) + 'mins '+
(s < 10 ? '0'+s : s) + 'secs';
}
// 1) 10800 seconds = 3600 * 3 = 3 hours
// 2) a+=10 increments seconds counter in 10-second interval
for ( var a = 0; a < 10800; a+=10 ) {
// an arbitrary date is chosen, we're more interested in time portion
var b = new Date('01/01/2000 04:00:00');
var c = new Date();
b.setTime(b.getTime() + a*1000);
// c is b + 9 seconds
c.setTime(b.getTime() + 9*1000);
$("#table1").append(
"<tr><td>" + fd(b) + ' - ' + fd(c) + "</td></tr>"
);
}
See the output here. I think you can port this code example to ASP.Net/VB.Net/C# easily.

Categories