how to convert "05:30" String value into integer using javascript - javascript

I tried to convert the string into integer using parseInt and parseFloat. But my string value is "+05:30" while using parseInt or parseFloat it converts it into 5, but I need exact conversion to 5.30. How could I do this?
My sample code is:
User.findAll({attributes: ['UTC offset'],
where: {
Timezone: { $like: '%'+address }
}
}).then(TimeZoneData => {
if(TimeZoneData.length != 0) {
var offset = parseFloat(TimeZoneData[0].dataValues['UTC DST offset']), // it return 5 only
}

Let's say the time zone offsets are valid, they are in hours and minutes always separated by a colon (':') and preceded by a '+' or '-'.
So
var utcOffset = "+05:30";
var a = uctOffset.split(':');
var hour = +a[0];
var minute = +a[1];
What you do with the hour and minute values is up to you - but if the hour is negative, the minutes might need to be made negative too. I suggest you use isNaN to check the minute is valid if it may be absent:
if( isNaN( minute)
minute = 0;

Related

determine if a timestamp in this format is within a particular range in JavaScript

I have a bunch of timestamps that have the following format: Year:Month:Day:Hour:Minute:Second, for example, 2017:01:01:23:59:59. All domains are zero-padded decimal numbers.
I am trying to write a function to determine if a given timestamp is within a range:
function isBetween(start, end, toCompare) {
}
for example, isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59") should return true as "2017:01:01:23:59:59" is between '2017:01:01:23:59:58' and "2017:01:02:23:59:58"
I couldn't find a clean way to do it. Can someone help me with this?
In JavaScript, Date objects can be compared fairly easily. However, as you've probably noticed, the format of the string you provided is not a format that can be parsed by JavaScript's Date object, so we will first have to fix that. Fortunately, this format is extremely predictable.
The first thing I notice is that the "Month" and "Date" are preceded by a zero if they're a single digit. This means that the date portion is always the exact same amount of characters (10). Because this is the case, we can use String.prototype.substring() to get the first 10 characters for the date, and get everything after the 11th character to get the time while skipping the colon in the middle.
var datetime = "2017:01:01:23:59:58";
var date = datetime.substring(0, 10);
var time = datetime.substring(11);
console.log("Date: " + date);
console.log("Time: " + time);
Now that they're separate, all we need to do is replace the colons in the date with forward slashes, then concatenate it with the time separated by a space. After this, we will have a date string in the MM/dd/yyyy hh:mm:ss format, which we can then parse using JavaScript's built in Date class.
var input = "2017:01:01:23:59:58";
var date = input.substring(0, 10).replace(/:/g, "/");
var time = input.substring(11);
var datetime = date + " " + time;
console.log(new Date(datetime));
Now we can throw this into it's own function, then use simple comparison to figure out if toCompare is between start and end.
function isBetween(start, end, toCompare) {
var startDate = convertDate(start);
var endDate = convertDate(end);
var compareDate = convertDate(toCompare);
return compareDate > startDate &&
compareDate < endDate
}
function convertDate(input){
var date = input.substring(0, 10).replace(/:/g, "/");
var time = input.substring(11);
var datetime = date + " " + time;
return new Date(datetime);
}
var between = isBetween("2017:01:01:23:59:58", "2017:01:02:23:59:58", "2017:01:01:23:59:59");
console.log(between)
This could work for you:
function isBetween(start, end, toCompare) {
start = dateGenerator(start)
end = dateGenerator(end)
toCompare = dateGenerator(toCompare)
if(start <= toCompare && toCompare <= end) return true
return false
}
function dateGenerator(str) {
str = str.split(":")
let date = new Date(`${str[0]}-${str[1]}-${str[2]}`)
date.setHours(str[3],str[4],str[5])
return date.valueOf()
}
const truthy = isBetween('2017:01:01:23:59:58', "2017:01:02:23:59:58", "2017:01:01:23:59:59")
console.log(truthy)
Firstly get individual values and add accordingly to Date constructor of JS and set the hours accordingly.
For comparison we can convert this unix figures (valueOf), hence it will be easier to compare.
This may seem as complex approach but it works.

How to convert '20211114025320+0000' to JS date object

I need to convert string: '20211114025320+0000' to JS Date object
(2021-11-14T02:53:20.000Z).
I have this format for info ('YYYYMMDDHHmmssZ')
maybe I need to use a custom function for this?
It looks like what you have is an ISO 8601 string with all the separators stripped away.
Therefore, a straight-forward way would be to add these separators back using a regex replace and then parsing it using the built-in parser:
function parseCustomDate (s) {
const isoString = s.replace(/^(....)(..)(..)(..)(..)(.*)$/, '$1-$2-$3T$4:$5:$6')
return new Date(isoString)
}
(Note that here the last capture group with the .* captures both seconds and the timezone specifier at once, because those don't need a separator between them anyway. To make it clearer, you could also use (..)(.*) and $6$7 instead of only (.*) and $6 as I did.)
Another way that is faster computationally but also more complex to read, understand and catch bugs in (in my opinion at least) would be to take the individual parts of the string and pass them to the Date.UTC constructor instead of going through the ISO string route:
function parseCustomDate (s) {
const year = Number(s.slice(0, 4))
const month = Number(s.slice(4, 6))
const day = Number(s.slice(6, 8))
const hour = Number(s.slice(8, 10))
const minute = Number(s.slice(10, 12))
const second = Number(s.slice(12, 14))
const tzSign = s.slice(14, 15)
const tzHour = Number(tzSign + s.slice(15, 17)) || 0
const tzMinute = Number(tzSign + s.slice(17, 19)) || 0
return new Date(Date.UTC(
year, month - 1, day,
hour - tzHour, minute - tzMinute, second
))
}
Explanation for the timezone handling here: JavaScript accepts "invalid" dates that have individual parts outside of the regular range by rolling them over, so e.g. 11:70:00 would become 12:10:00. This is why we can simply subtract the timezone parts (with each part also capturing the +/- sign), and we don't even have to mess with multiplying the minutes by 60 because we can handle them in the minutes part too.
I added the || 0 so that a string with a Z as timezone which would otherwise make tzHour and tzMinute NaN would also be handled as zero timezone offset.
A function to parse the string and pass the parts directly the Date constructor may be more efficient than parsing the string to generate another string that is then parsed by the built–in parser.
This method also avoids the built–in parser, which is usually considered a good idea.
// Parse YYYYMMDDHHmmss±HHmm or YYYYMMDDHHmmssZ
function parseTS(ts) {
// Get parts
let [C,Y,M,D,H,m,s,sign,oH,oM] = ts.match(/\d\d|\D/g);
// Deal with offset: ±HHmm or Z
if (sign == 'Z') {
sign = oH = oM = 0;
}
let oSign = sign == '+' ? -1 : +1;
// Create date from parts, adjust H, m for offset
return new Date(Date.UTC(C+Y, M-1, D, +H + oH*oSign, +m + oM*oSign, s));
}
['20211114082320+0530',
'20211114025320+0000',
'20211114025320Z',
'20211113225320-0400'
].forEach(ts => console.log(ts + '\n' + parseTS(ts).toISOString()));

Comparison of between hours using JavaScript

In my application I want to determine if a hour:minute is bigger than 21:00h and other hour:minute is lesser than 08:00.
I am using the 24-hour format for this.
var one = "21:30";
var two = "09:51";
To get just hour from hour and minutes I use split():
var h_1 = one.split(":"); //21
var h_2 = two.split(":"); //08
if (h_1 > "21" && h_2 < "08") {
// Do something
}
The real story for the application is:
A shop has an option to deliver outside of working time (working hours start at "08:00" - "21:00").
If a customer wants to buy out of hours, do something.
So why does my approach not work properly? What is the best approach to compare the hours and minutes between two variables of h:m type?
Have you tried comparing the strings?
if (two < "08:00" && one > "21:00")
//magic
As long as your strings are always formatted with a leading zero for one-digit hours, then it woks fine.
The split() method return an array, so to get just hours (first column in your case) you should specify index 0:
var h_1 = one.split(":")[0]; //21
var h_2 = two.split(":")[0]; // 08
i want to determine if hour:minute one is biger than 21:00h and hour:minute two is lesser than 08:00
Use greater than or equal to operator >= and less than or equal to <= to exclude hours 21 and 08:
if(h_1 >= "21" && h_2 <= "08") {
// do somthing
}
Hope this helps.

PHP date formating in JS

Im trying to figure out how to pass a date in the format of yyyy-mm-dd through JS that I have done in PHP before, but PHP and JS being different in this sense. I am at a bit of a loss.
Heres how I did it in PHP:
var default_dob = strtotime(date('m/d/Y', time()) .' -18 year');
var dob = date('m/d/Y', default_dob);
essentially taking todays date, subtracting 18 years, and reformatting it so its mm/dd/yyyy for a date picker. Idealy I'd like to avoid adding in another plugin to my already big stack of JS. So if I can do this without the extra weight (outside of being able to plug it into maybe a ready made function Ill be happy)
This will alert the date in your required format exactly 18 years back.
var date = new Date();
date.setFullYear(date.getFullYear() - 18);
alert(date.getFullYear() + '/' + (date.getMonth() + 1) + '/' + date.getDate());
Try this
<script type="text/javascript">
$ss= date('m/d/Y', strtotime('+18 year'));
?>
var default_dob = '<?php echo $ss;?>';
alert(default_dob);
</script>
// Left pad a string to the specified length using the specified character
function padLeft(str, length, char)
{
// Make sure args really are strings and that the length is a positive
// number. If you don't do this concatenation may do numeric addition!
str = String(str);
char = String(char) || ' '; // default to space for pad string
length = Math.abs(Number(length));
if (isNaN(length)) {
throw new Error("Pad length must be a number");
}
if (str.length < length) {
// Prepend char until the string is long enough
while (str.length < length) {
str = char + str;
}
// Make sure the string is the requested length
return str.slice(length * -1);
} else {
// The string is already long enough, return it
return str;
}
}
// Get the current date/time
// This is local to the browser, so it depends on the user's system time
var default_dob = new Date();
// Subtract 18 years
default_dob.setFullYear(default_dob.getFullYear() - 18);
// Format the string as you want it. PHP's d and m formats add leading zeros
// if necessary, in JS you have to do it manually.
var dob = padLeft(default_dob.getMonth(), 2, '0') + '/'
+ padLeft(default_dob.getDate(), 2, '0') + '/'
+ default_dob.getFullYear()
See also: MDN entry on the Date() object

Javascript calculation not correct

i have a weird problem in my javascript, take a look at my code below:
dateParts = document.getElementById('date').value.split('/');
newDays = 14;
year = dateParts[2];
month = parseInt(dateParts[1]) - 1;
day = parseInt(dateParts[0]) + parseInt(newDays);
alert(dateParts[0]+" + "+newDays+" = "+day);
and assume document.getElementById('date') = 07/01/2013
the calculation will give a correct result = 07 + 14 = 21
the calculation work fine at all date, except for 08/01/2013 / 09/01/2013
which the result is 08 + 14 = 14, any idea whats wrong here?
Your numbers are treated as octals, since you haven't used radix within parseInt()s. You need to adjust your parseInt()s like this:
month = parseInt(dateParts[1], 10) - 1;
day = parseInt(dateParts[0], 10) + parseInt(newDays, 10);
The leading 0 in 08 and 09 is causing JavaScript to assume the number is octal. Since those are not valid octal values, it treats them as 0. See this question for more details.
You should always use a radix when calling parseInt to avoid this problem.
the function is The parseInt(str, redix), if the value in the parseInt start with 0, it is assumed the radix is 8 so '09', '08' is invalid and the function returns 0. You need to call the function like parseInt('08', 10) to get the correct value.

Categories

Resources