Converting a string (150000) to time ( hh:mm:ss) in javascript - javascript

I am new to JS. Can anybody tell me whether is it possible to convert a string ( eg: "140000") to time (eg: 14:00:00) in Javascript.

You can do this:
Split your text into an array using the split method.
Map over your array and replace every item that has the index can be divided by to with the item + : using the map method.
Join your array to be string again using the join method.
Remove the last : from your result.
let convertToTime = str => str
.split("")
.map((item, index) => (index % 2 != 0) ? item + ':' : item)
.join("")
.slice(0, -1);
console.log(convertToTime("140000")); // 14:00:00
console.log(convertToTime("173003")); // 17:30:03
console.log(convertToTime("225510")); // 22:55:10
console.log(convertToTime("010201")); // 01:02:01

That's a bit tricky, because well... there is no Time object in Javascript.
There is only a Date object, although the name is kind of misleading, because the Date object contains both "Date" and "Time". There is a reason behind this seemingly confusing convention. I'm not going to go into too long of a detail, but to put it shortly, referencing "Time" is unreliable (to human brain).
For that, I'll just recommend reading this answer which explains it quite brilliantly.
Either way, this simple function will do the trick.
toDate(what){}
Upon sucessful string of time conversion, return a newly created Date object. Otherwise return -1. (or you could throw an Exception instead, up to you really)
var str = '143025';
function toDate(what){ // turns string into Date() object
var result;
if (what.length === 6) { // must be in HH:MM:SS length
var timearr = what.match(/.{1,2}/g); // splits time to HH:MM:SS array
if (timearr[0] <= 24 && timearr[1] <= 60 && timearr[2] <= 60){
return new Date('01 January 0001 ' + timearr[0] + ':'+
timearr[1] + ':' + timearr[2] + ' GMT'); // valid time format
}
}
return -1;
}
var mytime = toDate(str);
console.log(mytime.toUTCString());
Note, Date by itself is only expression of serialized numbers, if you want to return the time as result, you need to use the .toString or .toUTCString method from the Date.prototype object.

Related

Add 0 before single digit number of time format [duplicate]

This question already has answers here:
Adding "0" if clock have one digit
(9 answers)
Closed 3 years ago.
How can we add 0 before single digit number of time format.
Like if I have a time "0:3:25" (hh:mm:ss) format to convert into "00:03:25"
You shouldn't overcomplicate this:
const time = "0:3:25";
const paddedTime = time.split(':').map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
split the string by semicolons (:), that yields an array (hours, minutes, seconds). map this array with a function that adds a 0 before every item in the array, and slice the last two digits (you get an array again). Then join the resulting array by semicolons (and you get a string).
Or you could use a regex instead of the split:
const time = "0:3:25";
const paddedTime = time.match(/\d+/g).map(e => `0${e}`.slice(-2)).join(':')
console.log(paddedTime)
The last part is the same with regex (map, slice, join).
And you also could use the padStart() (JavaScript built-in function):
const time = "0:3:25";
const paddedTime = time.split(':').map(e => e.padStart(2, 0)).join(':')
console.log(paddedTime)
padStart() on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
You can do something like below (Explanations included):
const time = '0:3:25';
const correctedTime = parseTime(time);
console.log(correctedTime);
function parseTime(time){
return time
.split(':') // Split them into array as chunk of [hour, minute, second]
.map(pad) // Map them with `pad` function below
.join(':'); // Join them back into 'hh:mm:ss'
}
function pad(n){
return parseInt(n) < 10 // If number less than 10
? '0' + n // Add '0' in front
: n; // Else, return the original string.
}
you can add split the existing time string on the ":", then for each portion, add the "0" then take the last two characters. Then simply join the portions back into a striung.
let time = "0:3:25";
function updateTime(){
let newTimePortions = [];
let timePortions = time.split(":");
timePortions.forEach(function(portion,index) {
newTimePortions[index] = ("0" + portion).slice(-2)
})
return newTimePortions.join(':')
}
console.log(updateTime()); // gives 00:03:25
Please try below code
var dateinfo="0:3:25";
var newdate=dateinfo.split(":");
var hdate=newdate[0];
var mdate=newdate[1];
var sdate=newdate[2];
if(hdate.length == 1 ){
hdate="0"+hdate;
}
if(mdate.length == 1 ){
mdate="0"+mdate;
}
if(sdate.length == 1 ){
sdate="0"+sdate;
}
dateinfo=hdate+":"+mdate+":"+sdate;
This is work for me

Get most current data from Array JavaScript

I have a SP2010 list which contains a column with dates. (Date created).
I pull these using Spservices which comes in the following format:YYYY.MM.DD 00:00.
In the main function which reads the list I split the date so all that remains is YYYY.MM.DD.
dateAdded = ($(this).attr("ows_DatumActualiteit")).split(" ")[0];
The dates are then pushed in to an array for later filtering.
function selectMostRecentAct(datesIn){
var dateArray = [];
dateArray.push(datesIn);
for (var i = 0; i < dateArray.length; i++) {
console.log(dateArray[i]); //spits out all the dates in the array.
};
I want to select the most recent date in this array. How can I achieve this?
This question seems similar to yours:
What is the elegant way to get the latest date from array of objects in client side?
An alternative would be to loop through the whole array and compare the dates. As far as I know, you can use the <, >, == operators with dates.
dateArray.forEach((e) => {
if (e > latestDate)
latestDate = e;
});
console.log('Latest date is: ' + latestDate);
You need to sort the values then take the first element.
I'm assuming the format of your dates, but new Date is very lenient and should accept most reasonable inputs.
const dates = [
"2018-03-01T10:30:12.000Z",
"2018-03-01T12:11:49.000Z",
"2018-03-12T15:54:49.000Z",
"2018-03-09T19:12:49.000Z",
"2018-03-03T01:41:49.000Z",
];
const selectMostRecent = dates =>
dates.sort((a, b) => new Date(b) - new Date(a))[0];
console.log(selectMostRecent(dates));
Sort wants a comparison function that returns a value, either positive, negative or zero. When you perform arithmetic on a date value it is converted to epoch time (e.g. 1522096404277, milliseconds since 01/01/1970), and then subtracting these gives us the signed value we desire.
For example,
2018-03-09T19:12:49.000Z returns 1520622769000
2018-03-03T01:41:49.000Z returns 1520041309000
And when we do 2018-03-09T19:12:49.000Z - 2018-03-03T01:41:49.000Z (but those are coerced to numbers as described above) we get 581460000, meaning that the first date is sorted above the latter one.
Maybe something like this:
dateArray
.map(d => new Date(d.replace(/\./g, "-"))) // ISO format
.sort((a, b) => b - a) // Newest to oldest, probably
[0] // First!
This uses a reusable function for max; it should work for any values that you can compare with >. Note that it requires you to set a minimum value. For strings, "" (the empty string) seems appropriate. For numbers, you could use -Infinity, although that case is already covered by Math.max. For actual dates (not these dates formatted as strings), you can choose any date that would be well before any conceivable values, perhaps something like new Date(-1e15).
const max = (min) => vals => vals.reduce((curr, val) => val > curr ? val : curr, min)
const maxDate = max('')
console.log(
maxDate(['2014.07.23', '2014.08.29', '2007.03.25', '2017.09.30', '2008.02.29'])
)

Javascript function to convert UTF8 substring

Following up with JavaScript function to convert UTF8 string between fullwidth and halfwidth forms, this time I want to replace only part of the string.
I think I have found all the answers that I want (from previous post and Replace substring in string with range in JavaScript), but I just can't put it all together. Please take a look at the following demonstration:
// Extend the string object to add a new method convert
String.prototype.convert = function() {
return this.replace( /[\uff01-\uff5e]/g,
function(ch) { return String.fromCharCode(ch.charCodeAt(0) - 0xfee0); }
)
};
// Test and verify it's working well:
> instr = "!abc ABC!!abc ABC!"
"!abc ABC!!abc ABC!"
> instr.substr(5, 4)
"ABC!"
> instr.substr(5, 4).convert()
"ABC!"
// Great!
// Goal: define a decode method like this
String.prototype.decode = function(start, length) {
return this.replace(
new RegExp("^(.{" + start + "})(.{" + length + "})"), "$1" + "$2".convert());
};
// Test/verify failed:
> instr.decode(5, 4)
"!abc ABC!!abc ABC!"
// That failed, now define a test method to verify
String.prototype.decode = function(start, length) {
return this.replace(
new RegExp("^(.{" + start + "})(.{" + length + "})"), "$2".length);
};
> instr.decode(5, 4)
"2!abc ABC!"
I.e., I believe that all my string extending methods are defined properly (in the eyes of someone who doesn't know javascript several days ago). But when putting them together, they don't work as I expected (!abc ABC!!abc ABC!).
Further the last test, the one test with "$2".length, I just can't understand why "$2".length is 2 but not 4.
Please help me out.
Thanks a lot.
You can't do "$2".convert() and "$2".length when you define the regular expressions, it should be something like this
return this.replace(new RegExp(...), function(m1, m2) {
return m2.length;
});
so that the script worked dynamically on every matching result

Find the oldest date in a list of dates

I need a help in coming up with function in JavaScript. The function should be able to find the oldest date from the list of dates in this format yyyy-mm-dd hh:mm:ss. So the function would receive a text and among the lines it should find the oldest date entry and select text associated with that date.
Also if there is Java solution for this problem that could work to and I will use something to include Java inside JavaScript.
This'd work, assuming datelist is the string and that each date is on its own line:
var oldest = (function() {var o = ":", c, a=datelist.split(/\r?\n/); while(c=a.shift()) o = o < c ? o : c; return o;})();
Breaking that down, here's how it works: It's basically creating a function, running it, then getting its return value. The function is like so:
var o = ":",
// ":" comes after "9" in the character map, so it will be greater than any date
c, a = datelist.split(/\r?\n/);
// split on newlines, accomodating both \r and `\r\n` options.
while(c = a.shift()) {
// basically loop through each date
o = o < c ? o : c;
// if the current oldest date is older than the one we're looking at, keep the old one
// otherwise the new date is older so should be kept
}
return o;
// return the result
Here is how you would do it...
Iterate over the dates as an array, turning them into Unix epochs.
Find the oldest with Math.min.apply(Math, arrayOfDates) or better yet Math.min(...arrayOfDates).
You can convert all the date strings to Date objects, and then sort your list numerically and get the first item. Alternatively you can just apply Math.min on it to get the lowest value, if you don't need a sorted list.
var minDate = Math.min.apply(null, datestrings.map(Date));
Or, as your format does have leading zeroes, a simple string sort will do the same. To only search for a minimum string, you can use this:
var min = datestrings.reduce(function(min, cur) {
return cur < min ? cur : min;
});
A Wibbly-wobbly dollarsy-wollarsy example using jquery:
$("body").append($("<div>").attr("id", "q")); //some gratuitous jquery
var timelist = "2012-03-03 10:14:21 \r\n 2012-05-15 21:21:12\r\n 2012-07-01 10:19:19\r\n2012-02-11 21:21:12";
var datelist = timelist.split("\r\n");
var oldest = ":";
$.each(datelist, function (a) {
var trimmedThis = $.trim(this);
if (trimmedThis < latest) oldest = trimmedThis;
});
$("#q").text(oldest); //just to beef up the $ count

Javascript: Add +1 to number that starts with 0 (like 01, 02, 03) and keep the zero

I like to add (+1) to a number. But problem is my number can sometimes have 0 preceding it. Like 01, 02, 03, 04. So I like result to be:
mockup01 + 1 = mockup02
mockup11 + 1 = mockup12
How can that be achieved? Example of how I would use it would be if I had filename named mockup_01.htm and change it to mockup_02.htm
Thanks!
Maybe this
next = (parseInt(number, 10) + 101).toString().substr(1)
to make a mockup_02.htm out of mockup_01 try this
newName = fileName.replace(/\d+(?=\.)/, function(n) {
return (parseInt(n, 10) + Math.pow(10, n.length) + 1).toString().substr(1)
});
this works with numbers of any length, e.g. mockup_0001, mockup_000001 etc
I'm not a javascript programmer, but it seems like you're mixing up presentation and internal representation. If the "01" is a string, with a corresponding integer variable, you can convert from the string to the integer, add 1, and then make a new string with the desired formatting. This is sometimes referred to as a model-view-controller pattern. The model is the integer variable - it models the internal behavior of numbers. The view is the string - it presents the number in a human readable fashion. The controller handles the numerical operations.
function next_id(input) {
var output = parseInt(input, 10)+1; // parse and increment
output += ""; // convert to string
while (output.length<2) output = "0"+output; // prepend leading zeros
return output;
}
var id = "00";
for (var i=0; i<20; i++) {
console.log(id);
id = next_id(id);
}

Categories

Resources