How to retain leading zeroes when converting String to Number in javascript - javascript

How can I convert a string to number without loosing the trailing zeroes
var string1 = '02';
Number(string1); // == 2 - Default output
Number(string1); // == 02 - My requirement
The reason why I want this is: I am passing a date as value to the date HTML element. And the format is yyyy-MM-dd, month and date format is two digits and if I convert the date (string in my case) to number the leading zeroes are being removed.

You can't. A Number is a Number, period. You can make a helper object to have a number and a number leftpad method at your disposal. Something like:
document.querySelector("button").addEventListener("click", setDateValueExample);
var num = XNumber(3);
var result = {
el: document.querySelector("#result"),
log(str) {
this.el.textContent += str + '\n';
}
}
// XNumber usage example
result.log('XNumber(54).lpad(1000000): ' + XNumber(54).lpad(1000000));
// Datefield value from date field formatting example
var d = new Date(document.querySelector("#somedate").value);
result.log('Date formatted: ' +
[XNumber(d.getMonth()+1).lpad(),
XNumber(d.getDate()).lpad(),
d.getFullYear()].join('-'));
// Set date field value from string example
function setDateValueExample() {
document.querySelector("#somedate").value =
document.querySelector("button").getAttribute("data-dateString")
.split("/")
.reverse()
.map(function (v) {
return XNumber(v).lpad()
})
.join('-');
}
// The actual Number helper
function XNumber(num) {
return {
num: +num,
lpad (base) {
base = base || 10;
var len = (String(base).length - String(this.num).length)+1;
return len > 0 ? new Array(len).join('0')+this.num : this.num;
}
};
}
<input type="date" id="somedate" value="2017-02-01"/> a date
<button data-dateString="2/3/2017">Set value from string "2/3/2017"</button>
<pre id="result"></pre>

As commented, you can use ("00" + num).slice(-2).
You can try something like this:
function getParsedValue(date) {
var d = date;
if (typeof d === "string") {
d = new Date(date);
}
return [d.getFullYear(), getDoubleDigitString(d.getMonth() + 1), getDoubleDigitString(d.getDate())].join("-")
}
function getDoubleDigitString(num) {
return ("00" + num).slice(-2);
}
var date = new Date();
document.getElementById('txtDate1').value = getParsedValue(date)
document.getElementById('txtDate2').value = getParsedValue("1999/1/2")
<input type="date" id="txtDate1" />
<input type="date" id="txtDate2" />

Related

How to format a String to Date in React Native?

I am getting a Date as a String in this format from the server yyyyMMdd:hhmmss.
Is there a generic way to format this string to a Date object?
EDIT
formatDate = (data) => {
return data.slice(6, 8) + "." + data.slice(4, 6) + "." + data.slice(0, 4) + " " + data.slice(9, 11) + ":" + data.slice(11, 13)
}
The way you're reformatting the string is fine, even though it seems like a lot of code for a small job, slice is pretty fast. Some alternatives (not necessarily "better", just different):
// Reformat yyyyMMdd:hhmmss as dd.mm.yyyy hh:mm:ss
function formatMatch(s) {
let b = s.match(/\d\d/g) || [];
return `${b[3]}.${b[2]}.${b[0]}${b[1]} ${b[4]}:${b[5]}:${b[6]}`;
}
function formatReplace(s) {
return s.replace(/(\d{4})(\d{2})(\d{2}):(\d{2})(\d{2})(\d{2})/, '$3.$2.$1 $4:$5:$6');
}
formatDate = (data) => {
return data.slice(6, 8) + "." + data.slice(4, 6) + "." + data.slice(0, 4) + " " + data.slice(9, 11) + ":" + data.slice(11, 13)
}
let s = '20200323:123445';
console.log(formatDate(s));
console.log(formatMatch(s));
console.log(formatReplace(s));
If you want to get an actual Date object, then instead of using the bits to create another string, just pass them into the constructor:
// Parse yyyyMMdd:hhmmss to Date object
function parseD(s) {
let b = s.match(/\d\d/g) || [];
return new Date(b[0]+b[1], b[2]-1, b[3], b[4], b[5], b[6]);
}
let s = '20200327:134523';
console.log(parseD(s).toString());
The use of || [] means that if there's no match, an empty array is returned so all the b[*] terms return undefined and the result is an invalid date.
The above uses match, but slice or substring can be used the same way.

Replace char by coma and substrate 1 to the third value in JS

Supposing I have this:
var date = '2017-06-02';
How can I get:
var date = '2017,5,2';
So, I need to :
replace the - by ,
remove the leading zero if applied for the first and second parameter.
remove 1 for the second value
Thanks so much.
Non-ninjutsu solution:
var date = '2017-06-02';
var y = date.split("-")[0];
var m = date.split("-")[1];
var d = date.split("-")[2];
var final = y + "," + (parseInt(m)-1) + "," + parseInt(d);
console.log(final);
Try this
var date = '2017-06-02'
function convertDate(date){
var ddmmyy = date.split('-');
var withRemovedZero = ddmmyy.map(function(x){return parseInt(x)});
withRemovedZero[1] = withRemovedZero[1] -1;
return withRemovedZero.join(",");
}
console.log(convertDate(date))
var date = '2017-06-22';
var parts = date.split("-"); // split by '-' to get an array of parts
parts[0] = +parts[0]; // convert to number to remove any leading 0's
parts[1]--; // increment or decrement the part you need
parts[2] = +parts[2]; // convert to number to remove any leading 0's
var newDate = parts.join(","); // join the parts together using ','
console.log(newDate);
parts[1]-- is the same as parts[1] = parts[1] - 1 (parts[1] is the second part i.e. '06'). The parts ar strings, but whe using an operator that only applies on numbers such as -, then the part get converted to a number. If you use the + operator, however, this will cause a problem, as + wil be regarded as string concatination and not as numerical addition. A safter appraoch is to convert the string to a number first (either implicitly using unary + operator, or explicitly using parseInt or Number):
parts[1] = parseInt(parts[1]) - or + theNumberYouWant;
You can do a regular expression based string replacement. The following uses capturing groups to get the year, month and day, then uses a function to produce the replacement text.
var date = '2017-06-02';
var output = date.replace(/(\d+)-(\d+)-(\d+)/, function(_, y, m, d) {
return y + ',' + (m - 1) + ',' + +d;
});
console.log(output);
The result of the subtraction on the month is a number not a string, so it drops any leading zero automatically, then for the day I've used the unary plus operator to convert it to a number to drop its leading zero (if present), and both are concatenated into a string with the required commas.
Using split you can do that.
var date = '2017-06-02';
var date_array = date.split("-");
var first = date_array[1].charAt(0);
if(first=='0'){
first = date_array[1].substr(1);
}
else{
first = date_array[1];
}
var second = date_array[2].charAt(0);
if(second=='0'){
second = date_array[2].substr(1);
}
else{
second = date_array[2];
}
var output = date_array[0]+","+first+","+second;
document.write(output);
Output,
2017,6,2 // If date is 2017-06-02
2017,12,24 // If date is 2017-12-24

Date sort javascript

I have this code:
<script type="text/javascript">
function abc(objarray) {
objarray = objarray.sort(function (a, b) { return new Date(a).getTime() - new Date(b).getTime() });
alert(objarray);
}
objarray = ["16.08.1993 11:13", "16.08.1994 11:12", "13.08.1994 11:12", "13.08.1996 10:12", "08.08.1996 10:12"];
abc(objarray);
</script>
Date time format: dd.MM.yyyy HH:MM
I want to sort so that I can get the latest date first, but its not working.
You need to switch a and b and take another string for comparing, like
1993-08-16 11:13
the ISO 6801 data and time format, wich is comparable with String#localeCompare.
function abc(objarray) {
objarray = objarray.sort(function(a, b) {
function getISO(s) {
return s.replace(/(..).(..).(....) (.....)/, '$3-$2-$1 $4');
}
return getISO(b).localeCompare(getISO(a));
});
}
var objarray = ["16.08.1993 11:13", "16.08.1994 11:12", "13.08.1994 11:12", "13.08.1996 10:12", "08.08.1996 10:12"];
abc(objarray);
console.log(objarray);
Try this:
String.prototype.getCorrectDate = function () {
var date = this.split(' ')[0];
var hours = this.split(' ')[1];
var dateSplitted = date.split('.');
return new Date(dateSplitted[2] + '.' + dateSplitted[1] + '.' + dateSplitted[0] + ' ' + hours);
};
var dates = ["16.08.1993 11:13", "16.08.1994 11:12", "13.08.1994 11:12", "13.08.1996 10:12", "08.08.1996 10:12"];
var sorted = dates.sort(function(a, b) {
return b.getCorrectDate() - a.getCorrectDate();
});
alert('First from sorted: '+ sorted[0]);
alert('Last from sorted: '+ sorted[sorted.length - 1]);
https://jsfiddle.net/Lcq6wqhb/
Javascript's native method sort is used to sorting arrays, and we can pass callback function let's say sorting behavior(Sorting an array of JavaScript objects).
But before sorting we need to transform date strings to correct format, to be accepted new Date(dateString) as parameter, otherwise it gives error Invalid Date.
I'm transorming dd.mm.yyyy hh:MM to yyyy.mm.dd HH:MM using getCorrectDate method

regex a string, convert to number and match condition

I have this string:
002 2.0 (100aa) 95-97
I then want regex the 95-97 portion of it and paste it with relevant two numbers so I get a year.
In example, 96-97 should become 1995-1997, but 00-05 should become 2000-2005 (all numbers between 0 and 16 should be pasted with 20, but all other numbers with 19).
Then, when I have i.e. 1995-1997 I want to check if a year (i.e. 1996) is present inside 1995-1997 interval or not, and return a bolean.
How would one wright such code?
Best Regards
You could use the callback variant of replace:
function parseString(str) {
function padYear(year) {
return year < 30 ? 2000+year :
year < 100 ? 1900+year : year;
}
var result = {};
result.hasCurrentYear = false;
result.str = str.replace(/(\d\d)-(\d\d)$/g, function (match, yr1, yr2) {
yr1 = padYear(+yr1);
yr2 = padYear(+yr2);
var yrNow = (new Date).getFullYear();
result.hasCurrentYear = yrNow >= yr1 && yrNow <= yr2;
return yr1 + '-' + yr2;
});
return result;
}
var str = '002 2.0 (100aa) 95-16';
console.log(parseString(str));
Note that I made the split at year 30, as the solution will become outdated soon if you use 16 as split year.
I suppose there's a much simpler way to check if a certain year is in "range".The solution using String.split, Array.map functions and Number constructor:
var str = "002 2.0 (100aa) 95-97";
function checkYearInRange(str, year) {
year = Number(year);
var range = str.split(" ").pop().split('-').map((v) => Number((Number(v) > 16)? "19"+v : "20"+v));
return (range[0] <= year && year <= range[1]);
}
console.log(checkYearInRange(str, "1996")); // true
console.log(checkYearInRange(str, "2015")); // false

Re-write malformed dates yyyy-M-d to yyyy-MM-dd in javascript using RegEx

So I'm rewriting dates in javacript and as familiar js spits dates like 2013-1-1 that isn't very useful always. Instead I'm looking for a routine that will form this date to the correct iso-version 2013-01-01
Today I make this by using string
var b = new Date('2013-1-1');
var result = b.getFullYear() + "-" +
(b.getMonth().toString().length == 1 ? "0" + parseInt(b.getMonth() + 1) : parseInt(b.getMonth() + 1)) + "-" +
(b.getDate().toString().length == 1 ? "0" + b.getDate() : b.getDate());
This works but it is ugly. Is there a better way to perform this using RegEx?
Please spare me of any anti-regex comments
A non-regex solution would be a generic padding function. First get your date in the non-padded version then you can split on the separator and pad it as necessary. Something like this:
var date = '2013-1-1';
var pad = function(n) {
return function(str) {
while (str.length < n) {
str = '0'+ str;
}
return str;
}
};
date = date.split(/-/g).map(pad(2)).join('-'); //=> 2013-01-01
may be this could help:
var str="2013-1-1";
var m = str.match(/^(\d{4})-(\d{1})-(\d{1})$/);
console.log([m[1], "0".concat([2]-1), "0".concat(m[3])].join('-'));
based on elclanrs suggestion I wrote an extension method
// Add 0 to single numbers
Number.prototype.padDate = function () {
// Add +1 if input is 0 (js months starts at 0)
var number = this == 0 ? 1 : this;
return number.toString().length == 1 ? "0" + number : number;
};
This allows me to build dates like this
var b = new Date('2013-1-1');
var result = b.getFullYear() + "-" + b.getMonth().padDate() + "-" + b.getDate().padDate();
Much cleaner, thanks

Categories