How to format a String to Date in React Native? - javascript

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.

Related

Am I correct about .toFixed() and decimals?

I gave an example of using .tofixed() with math, functions, and arrays, to a beginner coder friend who has been reviewing these topics in his class.
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
};
bananaDivision();
They were understanding and following along no problem.
Then they asked me - "What if we put a decimal in the .toFixed ?"
So I ran:
const bananaX = 9;
const bananaY = 2.9768;
bananaArray = [bananaX , bananaY];
console.log("X before array = " + bananaX);
console.log("Y before array = " + bananaY + '\n')
console.log("X,Y after array = " + bananaArray + '\n')
console.log("Value of X in array: " + bananaArray[0]+ '\n')
console.log("Value of Y in array: " + bananaArray[1]+ '\n')
function bananaDivision (bananaArray){
console.log("Value of X after function = " + bananaX);
console.log("Value of Y after function = " + bananaY + '\n')
let bananaDivided = Math.abs(bananaX/bananaY );
console.log (`X divided by Y = + ${bananaDivided}` + '\n')
let bananaFixed = bananaDivided.toFixed(2);
let bananaFixed1 = bananaDivided.toFixed(.69420);
let bananaFixed2 = bananaDivided.toFixed(1.69420);
console.log("After using .toFixed(2) : " + bananaFixed + '\n');
console.log("After using .toFixed(.69420) : " + bananaFixed1 + '\n');
console.log("After using .toFixed(1.69420) : " + bananaFixed2 + '\n');
};
bananaDivision();
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
Am I correct? For my own curiousity, is there a crazy way to break .toFixed() so that it actually uses decimals? I'm experimenting atm but wanted to know if someone already figured that out.
I explained it as that .toFixed is looking at the first number within the () and that the decimals are ignored.
This would be correct. That is essentially what happens.
For full correctness, the input of toFixed() will be converted to an integer. The specification states that the argument must first be converted to a number - NaN will be converted to a zero. Numbers with a fractional part will be rounded down.
Which means that if you pass any number, you essentially get the integer part of it.
It also means that non-numbers can be used:
const n = 3;
console.log(n.toFixed("1e1")); // 1e1 scientific notation for 10
You're close, since toFixed() expects an integer it will handle converting decimal numbers before doing anything else. It uses toIntegerOrInfinity() to do that, which itself uses floor() so the number is always rounded down.
Most of Javascript handles type conversion implicitly, so it's something you should really understand well if you don't want to run into problems. There's a free book series that explains that concept and a lot of other important Javascript knowledge very well, it's called You Don't Know JS Yet.
just a demo how .tofixed works !!!!!!
function roundFloat(x, digits) {
const arr = x.toString().split(".")
if (arr.length < 2) {
return x
}else if(arr[1] === ""){
return arr[0]
}else if(digits < 1){
return arr[0]
}
const st = parseInt(x.toString().split(".")[1]);
let add = false;
const rudgt = digits
const fX = parseInt(st.toString().split("")[rudgt]);
fX > 5 ? add = true : add = false
nFloat = parseInt(st.toString().split("").slice(0, rudgt).join(""))
if (add) {
nFloat += 1
}
const repeat0 = (() => {
if (rudgt - st.toString().length < 0) {
return 0
}
return rudgt - st.toString().length
})()
const output = x.toString().split(".")[0] + "." + nFloat.toString() + "0".repeat(repeat0);
return output
}
console.log(roundFloat(1.200, 2))

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

How to retain leading zeroes when converting String to Number in 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" />

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