looping and print a list of time - javascript

var firstAm = '<li>12:00 AM</li>';
$('#time').append(firstAm);
for (i = 1; i < 12; i++) {
var am = '<li>' + i + ':00 AM</li>';
$('#time').append(am);
}
With above code I produced 1 hour interval, but I wish to produce something like
12:15 AM
12:30 AM
12:45 AM
which have 15 min different.
Fiddle : http://jsfiddle.net/ycjkqc0g/1/

You could do something like
var date = new Date();
date.setHours(0, 0, 0, 0);
var end = new Date(date);
end.setHours(end.getHours() + 12);
while (date < end) {
var am = '<li>' + convert24HourTo12Hour(date.getHours()) + ':' + date.getMinutes() + ' AM</li>';
$('#time').append(am);
date.setMinutes(date.getMinutes() + 15);
}
function convert24HourTo12Hour(h) {
return (h + 11) % 12 + 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="time"></div>

You can add one more loop inside the for loop as,
for (i = 1; i < 12; i++) {
for ( min = 0; min < 3; min++ ) {
var am = '<li>' + i + ':' + min * 15 + 'AM</li>';
$('#time').append(am);
}
}
In the inner loop you are basically printing the time in minutes as 0, 15, 30 and 45.
If you want to print it as '00' for hour, then you can format the number min*15 to a two digit value and use it.

var d = new Date();
d.setHours(0,0,0);
var html = '';
for (i=0;i<12*4*2;i++) {
var h = ('0'+d.getHours()).slice(-2);
var m = ('0'+d.getMinutes()).slice(-2);
var s = ('0'+d.getSeconds()).slice(-2);
var ampm = '';
if (h >= 12) {
ampm = 'pm';
} else {
ampm = 'am';
}
html += '<li>' + h + ':' + m + ':' + s + ' ' + ampm + '</li>';
d.setMinutes(d.getMinutes() + 15);
}
$(html).wrap('<ul></ul>');
$('#time').append(html);

Related

How to write a method which gives me future date time in format YYYY/MM/DD 12:30:50

I have written below method for this but it will fail when the current date will be 31.
I need to check if date is 31 it should return me 1st date of next month. Any help would be appreciated
getFutureDateTime: function () {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate() + 1;// to get current date remove "+1"
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
var dateTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
return dateTime;
},
It looks like you're trying to get the next day as a string. Your best bet is to let the Date object do the rollover between months and years for you, like this:
getFutureDateTime: function () {
var dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
var year = dt.getFullYear();
var month = dt.getMonth() + 1;
var day = dt.getDate();
var hour = dt.getHours();
var minute = dt.getMinutes();
var second = dt.getSeconds();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
var dateTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
return dateTime;
},
Note that if you're doing this in any vaguely modern environment, you can use padStart on the string (and padStart is easily polyfilled):
getFutureDateTime: function () {
var dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
var dateTime =
year.toString().padStart(2, "0") +
"/" +
month.toString().padStart(2, "0") +
"/" +
day.toString().padStart(2, "0") +
" " +
hour.toString().padStart(2, "0") +
":" +
minute.toString().padStart(2, "0") +
":" +
second.toString().padStart(2, "0");
return dateTime;
},
You could give yourself a utility function for the padding, to avoid repeating yourself:
function padZero2(val) {
return String(val).padStart(2, "0");
}
// ...
getFutureDateTime: function () {
var dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
var dateTime =
padZero2(year) +
"/" +
padZero2(month) +
"/" +
padZero2(day) +
" " +
padZero2(hour) +
":" +
padZero2(minute) +
":" +
padZero2(second);
return dateTime;
},
Similarly, if you use an ES2015 template literal, it may be a bit clearer:
getFutureDateTime: function () {
const dt = new Date();
dt.setDate(dt.getDate() + 1); // Will handle rollover for you
const dateTime = `${padZero2(year)}/${padZero2(month)}/${padZero2(day)} ${padZero2(hour)}:${padZero2(minute)}:${padZero2(second)}`;
return dateTime;
},
You don't need to have that complex function, look at this:
function getFutureDateTime() {
const regex = /(^[0-9-]+)(t)([^Z.]+)/i;
const date = new Date();
const isoFutureDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).toISOString();
const matches = iso.match(regex);
return matches[1] + ' ' + matches[3];
}
m= require("moment")
console.log(m().add("months",2).format("YYYY/MM/DD HH:MM:SS"))
use momentjs why to reinvent wheel when you already have some nodejs library for that you can change months to days , years etc to add days,houts,years etc instead of month
https://momentjs.com/guides/#/warnings/add-inverted-param/
You sould probably add an if statement before adding the '0' to test if day==32 => day = 1 and month = month+1
getFutureDateTime: function () {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate() + 1;// to get current date remove "+1"
if (day==32){
day = 1;
month = month + 1;
}
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if (month.toString().length == 1) {
month = '0' + month;
}
if (day.toString().length == 1) {
day = '0' + day;
}
if (hour.toString().length == 1) {
hour = '0' + hour;
}
if (minute.toString().length == 1) {
minute = '0' + minute;
}
if (second.toString().length == 1) {
second = '0' + second;
}
var dateTime = year + '/' + month + '/' + day + ' ' + hour + ':' + minute + ':' + second;
return dateTime;
},

How to get minutes on timestamp in jquery

I'd like to get a current timestamp object which is minutes l。 How do I do it with JavaScript?
Here my code :
var mins = "";
var new_timestamp = parseInt($("#current_time").data("timestamp")) + 1000;
var date = new Date(new_timestamp);
for (var b = 0; b < 60; b++) {
if (b == date.getMinutes()) {
str += "<option selected>" + (b < 10 ? ("0" + b) : b) + "</option>";
} else {
str += "<option>" + (b < 10 ? ("0" + b) : b) + "</option>";
}
}
$("#bank-order-time [name=\"minutes\"]").html(mins);
HTML :
<select name="minutes">
var date = new Date();
new Date() gives you a Date object of then time. You don't need to input a timestamp.
And date.getMinutes() give you the minute as you already know.
And if you need to get the current time again, remember you need to create a new Date object and do not use the old one.
My answer:
(function(){
var str ="";
var new_timestamp = parseInt($("#current_time").data("timestamp"))+1000;
var date = new Date(new_timestamp);
for( var a = 0; a < 24 ; a++)
{
if( a== date.getHours() )
{
str +="<option selected>"+(a<10?("0"+a):a)+"</option>" ;
}
else
{
str +="<option>"+(a<10?("0"+a):a)+"</option>" ;
}
}
$("#bank-order-time [name=\"hour\"]").html(str);
var mins = "";
for( var b = 0; b < 60; b++)
{
if( b == date.getMinutes())
{
mins +="<option selected>"+(b<10?("0"+b):b)+"</option>" ;
}
else
{
mins +="<option>"+(b<10?("0"+b):b)+"</option>" ;
}
}
$("#bank-order-time [name=\"minutes\"]").html(mins);
})();

Add seconds to formatted time from cell

I get this formatted time HH:MM:SS:MS.
$('#myTable').jqGrid('getCell', rowid, "time")
This give me a value from a cell. Lets say it is: 00:00:07:57 I want to add 30 seconds so it says: 00:00:37:57.
How I formate the time:
var date = new Date(seconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
var ms = date.getMilliseconds();
if (hh < 10) { hh = "0" + hh; }
if (mm < 10) { mm = "0" + mm; }
if (ss < 10) { ss = "0" + ss; }
if (ms < 10) { ms = "0" + ms; }
// This formats your string to HH:MM:SS:MS
ms = ((ms).toString().substr(0, 2));
var formattedTime = hh + ":" + mm + ":" + ss + ":" + ms;
I don't know why you're using a Date. Consider creating a function to convert the time to milliseconds and another to convert milliseconds back to the required time format. Then two formatted times can be added, e.g.
// Convert time in format hh:mm:ss:zz
// where zz is milliseconds
function timeToMs(s) {
var b = s.split(/\D/);
return b[0]*3.6e6 + b[1]*6e4 + b[2]*1e3 + b[3]*10;
}
// Convert milliseconds to time in format hh:mm:ss:zz
// where zz is milliseconds
function msToTime(ms) {
function z(n){return (n<10? '0' : '') + n;}
return z(ms/3.6e6|0) + ':' +
z((ms%3.6e6)/6e4|0) + ':' +
z((ms%6e4)/1e3|0) + ':' +
z((ms%1e3)/10|0);
}
// Add time in format hh:mm:ss:zz
// to time in format hh:mm:ss:zz
function addTime(t0, t1) {
return msToTime(timeToMs(t0) + timeToMs(t1));
}
var x = '02:01:01:10'; // time
var y = '00:00:30:00'; // add 30 seconds
document.write(x + ' + ' + y + ' = ' + addTime(x, y));
x = '00:00:07:57';
y = '00:00:30:00'; // add 30 seconds
document.write('<br>' + x + ' + ' + y + ' = ' + addTime(x, y));
x = '08:53:19:57';
y = '06:23:58:09';
document.write('<br>' + x + ' + ' + y + ' = ' + addTime(x, y));

Not getting date format using javascript

I want to get all dates in between 2 dates. So here I have mentioned statdate is date and end date is weekdate. In between 2 dates I want all dates.
Actully I am getting all dates But Not proper Format ,what i want in this format DD/MM/YY.
Now I am Getting in default Format (Sat Jun 09 2007 17:46:21)
$(document).ready(function () {
$("#day").click(function () {
startJsonSession();
return false;
});
function startJsonSession() {
var inputdate = $('#inputdate').val();
//alert("Input Date!!!" + inputdate );
var d = new Date(inputdate);
var nowMS = d.getTime(); // get # milliseconds for today
//alert(nowMS);
var week = 1000 * 60 * 60 * 24 * 7; // milliseconds in one week
//alert(week);
var oneWeekFromNow = new Date(nowMS + week);
//alert("oneWeekFromNow!!!" + oneWeekFromNow);
var fromdate = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (fromdate < 10) {
fromdate = "0" + fromdate;
}
if (month < 10) {
month = "0" + month;
}
//var date = fromdate + "/" + month + "/" + year;
var date = year + "/" + month + "/" + fromdate;
alert("InputDate!!!!" + date);
//var weekdate=oneWeekFromNow.getDate() + "/" + month + "/" + year;
var weekdate = year + "/" + month + "/" + oneWeekFromNow.getDate();
alert("weekdate!!!" + weekdate);
var tomorrow = new Date(d.getTime() + (24 * 60 * 60 * 1000));
var tomorrowdate = tomorrow.getDate();
var month1 = tomorrow.getMonth() + 1;
var year1 = tomorrow.getFullYear();
if (tomorrowdate < 10) {
tomorrowdate = "0" + tomorrowdate;
}
if (month1 < 10) {
month1 = "0" + month1;
}
//var nextday = tomorrowdate + "/" + month1 + "/" + year1;
var nextday = year1 + "/" + month1 + "/" + tomorrowdate;
alert("tomorrow!!!!" + nextday);
var d1 = new Date(date);
alert("D1!!!!!" + d1.);
var d2 = new Date(weekdate);
var aDates = [];
do {
aDates.push(d1.toString());
d1.setDate(d1.getDate() + 1);
}
while (d1 <= d2);
alert("Dates!!!" + aDates);
//alert(aDates.join("\n"));
}
});
You can do it in this way
$("#getDate").click(function () {
var start = $("#startdate").datepicker("getDate"),
end = $("#enddate").datepicker("getDate");
currentDate = new Date(start),
between = [];
while (currentDate < end) {
between.push(new Date(currentDate));
currentDate.setDate(currentDate.getDate() + 1);
}
for (var i = 0; i < between.length; i++) {
var date = $.datepicker.formatDate('dd/mm/yy', new Date(between[i]));
between[i] = date;
}
console.log(between)
})
Here 'between' is the array which contains all your required Date
SEE DEMO HERE
alert("Dates!!!" + aDates.getDate()+"/"+ (aDates.getMonth()+1)+"/"+ aDates.getFullYear());
You seem to want to get a array of date strings in d/m/y format given an input string in the same format. The following functions will do that.
// Parse a string in dmy format
// return a date object, NaN or undefined
function parseDMY(s) {
var b = s.match(/\d+/g);
if (b) {
return new Date(b[2], --b[1], b[0]);
}
}
// Given a date object, return a string in dd/mm/yyyy format
function formatDMY(date) {
function z(n){return (n<10? '0' : '') + n;}
return z(date.getDate()) + '/' + z(date.getMonth() + 1) + '/' + date.getFullYear();
}
function getWeekDates(s) {
var d = parseDMY(s);
var dates = [];
if (d) {
for (var i=0; i<7; i++) {
dates.push(formatDMY(d));
d.setDate(d.getDate() + 1);
}
return dates;
}
}
console.log(getWeekDates('7/7/2014').join());
// 07/07/2014,08/07/2014,09/07/2014,10/07/2014,11/07/2014,12/07/2014,13/07/2014
Note that adding 1 day to a date is preferred over adding milliseconds as it allows the Date object to take account of daylight saving changes that might be involved.

Passing Date argument to function

How to pass argument of Date to another function? My code:
var myDate = new Date(data.GetOPCResult.DateTime.match(/\d+/)[0] * 1);
var datlabel = document.getElementById("ct");
datlabel.innerHTML = GetTime(myDate);
And GetTime function code:
function GetTime(DateTime) {
var month = (DateTime.getMonth() < 10) ? "0" + (DateTime.getMonth() + 1) : (DateTime.getMonth() + 1);
var day = (DateTime.getDate() < 10) ? "0" + DateTime.getMonth() : DateTime.getMonth();
var hour = (DateTime.getHours() < 10) ? "0" + DateTime.getHours() : DateTime.getHours();
var minute = (DateTime.getMinutes() < 10) ? "0" + DateTime.getMinutes() : DateTime.getMinutes();
var second = (DateTime.getSeconds() < 10) ? "0" + DateTime.getSeconds() : DateTime.getSeconds();
return DateTime.getDate() + "." + month + "." + DateTime.getFullYear() + " " + hour + ":" + minute + ":" + second;
}
This works for me
function GetTime(d) {
var month = (d.getMonth() < 10) ? "0" + (d.getMonth() + 1) : (d.getMonth() + 1);
var day = (d.getDate() < 10) ? "0" + d.getMonth() : d.getMonth();
var hour = (d.getHours() < 10) ? "0" + d.getHours() : d.getHours();
var minute = (d.getMinutes() < 10) ? "0" + d.getMinutes() : d.getMinutes();
var second = (d.getSeconds() < 10) ? "0" + d.getSeconds() : d.getSeconds();
return d.getDate() + "." + month + "." + d.getFullYear() + " " + hour + ":" + minute + ":" + second;
}
alert(GetTime(new Date()));
Are you sure you are passing a valid Date object? Try passing new Date() instead of myDate to your GetTime. If that works, your myDate variable is not a valid Date object.
Your code is fine. A little re-factoring will help though.
function GetTime(date) {
var day = zeroPad(date.getDate(), 2);
var month = zeroPad(date.getMonth() + 1, 2);
var year = zeroPad(date.getFullYear(), 4);
var hour = zeroPad(date.getHours(), 2);
var minute = zeroPad(date.getMinutes(), 2);
var second = zeroPad(date.getSeconds(), 2);
return day + "." + month + "." +
year + " " + hour + ":" +
minute + ":" + second;
}
function zeroPad(num, count) {
var z = num + '';
while (z.length < count) {
z = "0" + z;
}
return z;
}
Also please check what is data.GetOPCResult.DateTime. I would say this will do.
var myDate = new Date( (data.GetOPCResult.DateTime || "")
.replace(/-/g,"/")
.replace(/[TZ]/g," ") );

Categories