Java/ Javascript from String to time - javascript

I want to do some time manipulation which to add 30 minutes to the time given in String format, so I do some test data to print from 12.00am to 12.00pm.The following code produce unsatisfied result which will auto remove the "0" if less than 9.
ConvertTimeformat("24", "12.00am");
function ConvertTimeformat(format, time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/\.(\d+)/)[1]);
var AMPM = time.match(/\D(\D.*)$/)[0];
var a = document.getElementById("time");
var text = "";
if (AMPM == "pm" && hours < 12)
hours = hours + 12;
if (AMPM == "am" && hours == 12)
hours = hours - 12;
for(var i = 1;i <= 48; i++){
minutes += 30;
if(minutes == 60){
hours += 1;
minutes = 00;
}
text += hours+""+minutes+"<br/>";
}
a.innerHTML = text;
}
<html>
<head></head>
<body>
<p id="time"><p>
</body>
</html>
I try to do the following to add if-statement, to add "0" if less the 9, but the result was terrible.
ConvertTimeformat("24", "12.00am");
function ConvertTimeformat(format, time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/\.(\d+)/)[1]);
var AMPM = time.match(/\D(\D.*)$/)[0];
var a = document.getElementById("time");
var text = "";
if (AMPM == "pm" && hours < 12)
hours = hours + 12;
if (AMPM == "am" && hours == 12)
hours = hours - 12;
for(var i = 1;i <= 48; i++){
minutes += 30;
if(minutes == 60){
hours += 1;
minutes = 00;
}
if(minutes == 0){
minutes = "00";
}
if(hours <= 9){
hours = "0" + hours;
}
text += hours+""+minutes+"<br/>";
}
a.innerHTML = text;
}
<html>
<head></head>
<body>
<p id="time"><p>
</body>
</html>
Anyone have ideas to modify my code to look more better? This code will be use in Java as well, so how is the syntax run? Same as Javascript? Thank you
[UPDATE] The expected outcome should be:
0000
0030
0100
0130
.
.
.
0000

Related

How to display Good Morning/Afternoon/Evening using javascript in 12hours format

It is 4:11PM here now but my output is shown as 'Good Morning' - why is this happening?
$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var h = ndate.getHours() % 12;
var format = h >= 12 ? 'PM' : 'AM';
var m = ndate.getMinutes().toString();
var s = ndate.getSeconds().toString();
if (h < 12) {
h = "0" + h;
$("h3.day-message").html("Good Morning");
} else if (h < 18) {
$("h3.day-message").html("Good Afternoon");
} else {
$("h3.day-message").html("Good Evening");
}
if (s < 10) {
s = "0" + s;
}
if (m < 10) {
m = "0" + m;
}
$('.date').html(h + ":" + m + ":" + s + format);
}
setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
The issue is because you are using the modulo operator. This means that your h > 12 check will never be hit as the remainder of the division cannot be greater than 12. It's because of this your logic always believes it's still the morning. To fix this, just use a simple < check when comparing the hour figure.
Also note that you have some issues with the formatting of the date, such as appending extra zeroes so you end up with 011 as hour values. You can fix this by using slice().
With all that said, try this:
$(document).ready(function() {
function dateTime() {
var ndate = new Date();
var hours = ndate.getHours();
var message = hours < 12 ? 'Good Morning' : hours < 18 ? 'Good Afternoon' : 'Good Evening';
$("h3.day-message").text(message);
$('.date').html(hours.leadingZeroes(2) + ":" + ndate.getMinutes().leadingZeroes(2) + ":" + ndate.getSeconds().leadingZeroes(2) + (hours < 12 ? 'AM' : 'PM'));
}
setInterval(dateTime, 1000);
});
Number.prototype.leadingZeroes = function(len) {
return (new Array(len).fill('0', 0).join('') + this).slice(-Math.abs(len));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
$(document).ready(function() {
function dateTime() {
var format="";
var ndate = new Date();
var hr = ndate.getHours();
var h = hr % 12;
if (hr < 12)
{
greet = 'Good Morning';
format='AM';
}
else if (hr >= 12 && hr <= 17)
{
greet = 'Good Afternoon';
format='PM';
}
else if (hr >= 17 && hr <= 24)
greet = 'Good Evening';
var m = ndate.getMinutes().toString();
var s = ndate.getSeconds().toString();
if (h < 12) {
h = "0" + h;
$("h3.day-message").html(greet);
} else if (h < 18) {
$("h3.day-message").html(greet);
} else {
$("h3.day-message").html(greet);
}
if (s < 10) {
s = "0" + s;
}
if (m < 10) {
m = "0" + m;
}
$('.date').html(h + ":" + m + ":" + s + format);
}
setInterval(dateTime, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3 class="day-message"></h3>
<span class="date"></span>
You are calculating mode, so h will never be greater that 12
So, Instead of
var h = ndate.getHours() % 12;
Use it
var h = ndate.getHours();
Explaination: modulo operator(%) will divide total hours by 12 and return the Remainder.
For example if current time is 4 pm, I'll be 16 hours, so It'll return 4
Without jQuery
const messages = [
{ ampm: "am", "greet": 'Good Morning' },
{ ampm: "pm", "greet": 'Good Afternoon' },
{ ampm: "pm", "greet": 'Good Evening' }
];
window.addEventListener("DOMContentLoaded", () => {
const dateSpan = document.getElementById("date");
const message = document.getElementById("day-message");
const dateTime = () => {
let now = new Date(),
hour = now.getHours(),
hh = hour % 12, // (hour % 12).toString().padStart(2,"0") if you want leading 0
mm = now.getMinutes().toString().padStart(2,"0"),
ss = now.getSeconds(),
period = 0;
if (hour < 12) period = 0;
else if (hour >= 12 && hour < 17) period = 1;
else if (hour >= 17 && hour <= 24) period = 2;
message.textContent = messages[period].greet;
dateSpan.textContent = `${hh}:${mm}${messages[period].ampm}`;
};
setInterval(dateTime, 500);
});
<h3 id="day-message"></h3>
<span id="date"></span>
Display Good Morning/Afternoon/Evening using javascript in 12hours format
const displayGreeting =()=>{
const myDate = new Date();
const hrs = myDate.getHours();
let greet;
if (hrs < 12)
greet = 'Good Morning';
else if (hrs >= 12 && hrs <= 17)
greet = 'Good Afternoon';
else if (hrs >= 17 && hrs <= 24)
greet = 'Good Evening';
return greet
}

How to get a "0" before "1" to "9" in a clock

My clock script is as follows. For some reason if(minutes<10){minutes="0"+minutes;} and if(seconds<10){seconds="0"+seconds;} will add a 0 before a number less than 10, but it won't do it for the hours. Any advice on how to fix it?
<script>
function TimeUpdate() {
var now = new Date(), hours = now.getHours(), minutes = now.getMinutes(), seconds = now.getSeconds();
// The 1st "if" does not work.
if (hours < 10) {hours = "0" + hours;}
if (minutes < 10) {minutes = "0" + minutes;}
if (seconds < 10) {seconds = "0" + seconds;}
// (This works) AM or PM option
if (hours >= 12 && hours < 24) {var TimeOfDay = "PM";}
else {var TimeOfDay = "AM";}
// (This works) Converts the hours from 24 to 12
if (hours > 12) {hours = hours - 12;}
// This sets the hours to a specific number.
// This is used only for this demonstration.
hours = 5;
// (This works) Puts everything together
var CurrentTime = hours + ':' + minutes + ':' + seconds + " " + TimeOfDay;
// (This works) The clock <div>
var MyClock = document.getElementById('clock');
// (This works) Writes the "CurrentTime" to the clock's <div>
MyClock.innerHTML = CurrentTime;
var t = setInterval (function () {TimeUpdate ()}, 1000);
}
// (This works) This loads the clock onto the page.
window.onload = TimeUpdate;
</script>
<p id="clock"></p>
You're overwriting your check. Move that block of code further down:
function TimeUpdate() {
var now = new Date(),
hours = now.getHours(),
minutes = now.getMinutes(),
seconds = now.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// (This works) AM or PM option
if (hours >= 12 && hours < 24) {
var TimeOfDay = "PM";
} else {
var TimeOfDay = "AM";
}
// (This works) Converts the hours from 24 to 12
if (hours > 12) {
hours = hours - 12;
}
// This sets the hours to a specific number.
// This is used only for this demonstration.
hours = 5;
// The 1st "if" does not work.
if (hours < 10) {
hours = "0" + hours;
}
// (This works) Puts everything together
var CurrentTime = hours + ':' + minutes + ':' + seconds + " " + TimeOfDay;
// (This works) The clock <div>
var MyClock = document.getElementById('clock');
// (This works) Writes the "CurrentTime" to the clock's <div>
MyClock.innerHTML = CurrentTime;
var t = setInterval(function() {
TimeUpdate()
}, 1000);
}
// (This works) This loads the clock onto the page.
window.onload = TimeUpdate;
<br>
<br>
<br>
<p id="clock"></p>
You need to place
if (hours < 10) {
hours = "0" + hours;
}
after
if (hours > 12) {
hours = hours - 12;
}
since it has to be true for hours of 13-21 (1-9 PM) as well.
Watch out for that code. That's a recursive function, you'll blow your computer memory in no time. Please remove the TimeUpdate() from inside itself
function TimeUpdate() {
var now = new Date(),
hours = now.getHours(),
minutes = now.getMinutes(),
seconds = now.getSeconds();
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// (This works) AM or PM option
if (hours >= 12 && hours < 24) {
var TimeOfDay = "PM";
} else {
var TimeOfDay = "AM";
}
// (This works) Converts the hours from 24 to 12
if (hours > 12) {
hours = hours - 12;
}
// This sets the hours to a specific number.
// This is used only for this demonstration.
hours = 5;
// The 1st "if" does not work.
if (hours < 10) {
hours = "0" + hours;
}
// (This works) Puts everything together
var CurrentTime = hours + ':' + minutes + ':' + seconds + " " + TimeOfDay;
// (This works) The clock <div>
var MyClock = document.getElementById('clock');
// (This works) Writes the "CurrentTime" to the clock's <div>
MyClock.innerHTML = CurrentTime;
}
// (This works) This loads the clock onto the page.
var t = setInterval(function() {
TimeUpdate()
}, 1000);
<br>
<br>
<br>
<p id="clock"></p>

javascript shipping countdown fails if i use a target of 14:30

I use the following javascript to show a countdown timer for shipping that day
var timerRunning = setInterval(
function countDown() {
var target = 14; // This is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
var despatchday = 'TODAY!';
if (weekday == 0) { //Sunday? Add 24hrs
target += 24;
despatchday = 'on Monday';
} //keep this before the saturday, trust me :>
if (weekday == 6) { //It's Saturday? Add 48hrs
target += 48;
despatchday = 'on Monday';
}
if ((weekday == 5) && (now.getHours() > target) && (now.getHours() <= 24)) {
target += 72;
despatchday = 'on Monday';
}
//If between Monday and Friday,
//check if we're past the target hours,
//and if we are, abort.
if ((weekday >= 1) && (weekday <= 5)) {
if ((now.getHours() > target) && (now.getHours() <= 24)) { //stop the clock
target += 24;
despatchday = 'tomorrow';
} else if (now.getHours() > target) { //stop the clock
return 0;
despatchday = 'today';
}
}
var hrs = (target) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = 'Order in the next ' + hrs + 'hrs ' + mins + 'mins ' + secs + 'secs for despatch ' + despatchday;
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
The problem I have is that if I set the cut off time to anything other than a full hour the timer does not work.
The correct output is Order in the next xx hrs, xx mins xx secs for despatch today
If I set
var target = 14; // This is the cut-off point
as 14:30 it gives "Just checking the time"
I assumed that it needed the mins as a decimal but if I set it as 14.5 it is adding 0.5 hrs to the output; ie 23.5hrs 50mins 30secs
I have set up a fiddle here. http://jsfiddle.net/4eu4o6k0/
Ideally I need it to be able to handle time in the format of hh:mm as that is the format of the time stored in the database. Is there a correct way to process partial hours in this type of script?
you need to hand the decimal place of hrs:
var rem =hrs%1;
mins = mins + (rem*60);
hrs = hrs - rem;
if (mins > 59) {
mins = mins - 60;
hrs= hrs +1;
}
Also I think you meant to spell dispatch
I'd personally advise against writing own code for handling time intervals because it's known to be error-prone. Use moment.js or date.js for such things
Here's sample for Moment.js

Javascript date time two hours off

I have a javascript code set into my webpage but the date time is always two hours off. If anyone knows what's wrong please help.
Here's my relevant JavaScript code:
function show() {
var Digital = new Date()
var hours = Digital.getHours()
var minutes = Digital.getMinutes()
var seconds = Digital.getSeconds()
var dn = "AM"
if (hours > 12) {
dn = "PM"
hours = hours - 12
}
if (hours == 0) c
hours = 12
if (minutes <= 9)
minutes = "0" + minutes
if (seconds <= 9)
seconds = "0" + seconds
document.dform.currenttime.value = hours + ":" + minutes + ":" + seconds + " " + dn
setTimeout("show()", 1000)
}
show();
You have a c right here:
if (hours==0)c
Delete the c. It works. You're welcome.
I suggest proofreading your code before you come asking for help, but more importantly you should format your code so that it's legible enough to proofread. As an example:
function show() {
var Digital = new Date();
var hours = Digital.getHours();
var minutes = Digital.getMinutes();
var seconds = Digital.getSeconds();
var dn = "AM";
if(hours > 12) {
dn = "PM";
hours -= 12;
}
if(hours == 0) hours = 12;
if(minutes <= 9) minutes = "0" + minutes;
if(seconds <= 9) seconds = "0" + seconds;
document.dform.currenttime.value = hours + ":" + minutes + ":" + seconds + " " + dn;
}
var clock = setInterval(show, 1000);
This is easier to read and you likely would've noticed the erroneous c.

JavaScript Clock Not displaying Correctly

I'm having an issue where I have a digital sign and it accepts embedded HTML. I created a widget for it to display a clock, I tried downloading one and they never worked for some reason so made my own. The issue that I am having is that the clock does not display the correct time. I got it so the numbers display correctly but the issue that I am seeing now is that it will dsiplay AM instead of PM. I would appreciate any help, not sure if the logic is right or if I used the wrong condition statements. Any help would be awesome, Thanks!
<script type="text/javascript">
function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var p;
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
if (hours >= 12){
p = "PM"; //could not get this in it's own if statement w/o breaking it
hours = (hours - 12);
}
if (hours == 0) {
hours = (hours + 12);
}else {
p = "AM";
}
var v = hours + ":" + minutes + ":" + seconds + " " + p;
setTimeout("updateTime()", 1000);
document.getElementById('time').innerHTML= v;
}
updateTime();
</script>
<style type="text/css">
#time {
font-size: 5em;
}
</style>
<div><span id="time"></span></div>
change your IFs to:
if (hours >= 12) {
p = "PM";
hours = (hours>12) ? (hours - 12) : 12;
}
else
{
if (hours == 0)
hours = 12;
p = "AM";
}
Your code was almost right, there is just one little mistake you're making. when you check if hours is greater than 12, p is PM else p should be AM. You can solve this by setting p to AM at the beginning of the function, of moving the else you already have up right after the check.
This Fiddle will demonstrate a working example: http://jsfiddle.net/s2R9y/
if (hours >= 12) {
p = "PM";
hours = (hours - 12);
} else {
p = "AM";
}
The setTimeOut function has been fixed aswell, so it actually worked:
setTimeout(updateTime, 1000);

Categories