How to get minutes on timestamp in jquery - javascript

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);
})();

Related

Cumbersome time parsing in JavaScript

I need a function to convert time in text from a format with day-part letters to digits.
E.g. 4:15PM -> 16:15, 4:15AM -> 4:15AM. Currently I have the following solution
function formatTime(text){
var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9] (AM|PM)';
var reg = new RegExp(find, 'g');
pos = 0;
var result;
var formatedText = "";
while((result = reg.exec(text)) !== null) {
if(result[2] == "PM"){
var hours= parseInt(result[0], 10);
hours = hours + 12;
var hoursStr = hours.toString();
var newTime = hoursStr + result[0].substring(result[1].length,result[0].length - 3);
formatedText += newTime;
pos = reg.lastIndex;
} else {
formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
pos = reg.lastIndex;
}
}
if(pos < text.length){
formatedText += text.substring(pos, text.length);
}
return formatedText;
}
console.log(formatTime("Some Text (11:00AM - 1:00PM)"));
I makes nicely cases like
console.log(formatTime("Some Text (11:00AM - 1:00PM)"));
But I strugle to make it process
console.log(formatTime("Some Text (11:00 AM - 1:00 PM)"));
This works for your examples.
I've added \\s? to the regex and made a minor change in the logic of cutting time (-2 instead of -3). Also I've moved variables definition to the beginning of the function to reflect hoisting in JavaScript.
function formatTime(text){
var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]\\s?(AM|PM)';
var reg = new RegExp(find, 'g');
var pos = 0;
var formatedText = "";
var result, hours, hoursStr, newTime;
while ((result = reg.exec(text)) !== null) {
if (result[2] === "PM") {
hours= parseInt(result[0], 10);
hours = hours + 12;
hoursStr = hours.toString();
newTime = hoursStr + result[0].substring(result[1].length, result[0].length - 2);
formatedText += newTime;
} else {
formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
}
pos = reg.lastIndex;
}
if (pos < text.length) {
formatedText += text.substring(pos, text.length);
}
return formatedText;
}
Here's an easier way to do this: Just use two functions. One to convert the hours, and another to match against PM times along with the replace() function.
Easy does it...
function convertTime12to24(time12h) {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (hours === '12') {
hours = '00';
}
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return hours + ':' + minutes;
}
function formatTime(i_string) {
console.log(i_string.replace(/([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])(PM)/gi, function newDate(x) {
return convertTime12to24(x.replace("PM", " PM"))
}));
}
formatTime("The time is now 4:15PM");
formatTime("The time is now 12:15PM");
formatTime("The time is now 4:00AM");
formatTime("The time is now 12:00AM");
formatTime("The time is now 11:00PM");

Output all dates of a year

I would like to list all dates and hour of a year with format mmddhh
Q1: Why I got "undefined" before the output? How can I fix it?
var m, d, h, month, day, hour, output;
for (m = 1; m <= 12; m++) {
month = addZero(m).toString();
for (d = 1; d <= 31; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
}
document.getElementById("result").innerHTML = output;
function addZero(z) {
var z
if (z < 10)
return "0" + z;
else
return z;
}
<p id="result"></p>
Q2: I tried looping d 31 times using if (m = "01" || "03" || "05" || "07" || "08" || "10" || "12") else looping 30 times. However it is fail, how can I do that?
var m, d, h, month, day, hour, output;
for (m = 1; m <= 12; m++) {
month = addZero(m).toString();
if (m = "01" || "03" || "05" || "07" || "08" || "10" || "12") {
for (d = 1; d <= 31; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
} else {
for (d = 1; d <= 30; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
}
}
document.getElementById("result").innerHTML = output;
function addZero(z) {
var z
if (z < 10)
return "0" + z;
else
return z;
}
<p id="result"></p>
You have declared a variable called output, but it is not initialized with a value, so its value is undefined.
Then when you say output += month + day + hour + "<br>"; it is really output = undefined + month + day + hour + "<br>";, thus you are getting an undefined at the beginning of the output
var m, d, h, month, day, hour, output = "";
for (m = 1; m <= 12; m++) {
month = addZero(m).toString();
for (d = 1; d <= 31; d++) {
day = addZero(d).toString();
for (h = 1; h <= 24; h++) {
hour = addZero(h).toString();
output += month + day + hour + "<br>";
}
}
}
document.getElementById("result").innerHTML = output;
function addZero(z) {
var z
if (z < 10)
return "0" + z;
else
return z;
}
<p id="result"></p>

looping and print a list of time

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);

Display next 5 days excluding Sundays in javascript

I am displaying the following code for next 5 days
function setDateTime() {
var timesOffice = (officeTimes[officeID] + "").split(",");
//alert(officeTimes[officeID]+":12:"+timesOffice[0]);
var dt = new Date(correctDate);
var dateOptions = "";
var firstdateString = "";
var totalDays = 5;
for (i = 0; i < totalDays; i++) {
var sateString = dt.getFullYear() + " " + monthNames[dt.getMonth()] + " " + (dt.getDate());
//console.log("i:"+i+"s:"+sateString);
dateFlag = 0;
var j = 0;
for (j = 0; j < timesOffice.length; j++) {
if (checkValidDateTime(sateString, timesOffice[j])) {
dateFlag = 1;
break;
}
}
dt.setDate(dt.getDate() + 1);
if (dateFlag == 0) {
totalDays++;
continue;
}
if (firstdateString == "") firstdateString = sateString;
dateOptions = dateOptions + '<option value="' + sateString + '">' + sateString + '</option>';
}
$(".date").html(dateOptions);
}
I want to exclude Sundays from this list
You can tell what day of the week a Date instance represents using its getDay function:
if (dt.getDay() === 0) {
// It's Sunday
}
else {
// It isn't
}
I figure you can take it from there... :-)
You can use the getDay method to get the day of the week:
function setDateTime() {
var timesOffice = (officeTimes[officeID] + "").split(",");
//alert(officeTimes[officeID]+":12:"+timesOffice[0]);
var dt = new Date(correctDate);
var dateOptions = "";
var firstdateString = "";
var totalDays = 5;
int i=0;
while(i<totalDays) {
if(dt.getDay() != 0) // exclude Sundays
{
var sateString = dt.getFullYear() + " " + monthNames[dt.getMonth()] + " " + (dt.getDate());
//console.log("i:"+i+"s:"+sateString);
dateFlag = 0;
var j = 0;
for (j = 0; j < timesOffice.length; j++) {
if (checkValidDateTime(sateString, timesOffice[j])) {
dateFlag = 1;
break;
}
}
if (firstdateString == "") firstdateString = sateString;
dateOptions = dateOptions + '<option value="' + sateString + '">' + sateString + '</option>';
i++;
}
dt.setDate(dt.getDate() + 1);
}
$(".date").html(dateOptions);
}
As T.J Crowder said, you can use Date.getDay() to get the current weekday in the week. Giving some integer from 0 to 6 where 0 is Sunday and 6 is Saturday.
To show the next weekdays I supposed we don't want to print a bunch of numbers on the screen, so we can use a weekdays array to go from numbers to their corresponding text:
var weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
Now we can just use a for loop to scroll through these, starting from the todays day you get from using .getDay(). Note that if you go over we want to go back to 0, so I'll use a separate variable j in the loop for that:
var weekdays = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var date = new Date();
var day = date.getDay(); // Current day
var numDays = 5; // Number next days
for(var i = day; i <= day + numDays; i++ ) {
var j = i;
j = j % weekdays.length;
console.log(weekdays[j]);
}
To show it can overflow and move back to Sunday, Here is a fiddle that prints the next 20 days.
To exclude Sunday, simply check that if(j != 0) , then print:
for(var i = day; i <= day + numDays; i++ ) {
var j = i;
j = j % weekdays.length;
if( j != 0 )
console.log(weekdays[j]); // Only prints non-Sundays
}
Although since today is Sunday, suppose you want to include Today's Sunday, but not the next Sundays. Simply change the if statement to if( j != 0 || i == 0 ), which will make an exception for the first element. Here is an example of that.

How to create a timestamp with javascript

I want to use a timestamp as an update indicator(last updated at), so i need a current time, month/day/year/hours/minutes/seconds, but the date() returns an live value. Is there a way to do this?
UPDATE: the idea is like this http://web.student.tuwien.ac.at/~e9125168/javas/jstamp.html (this shows a last modified time, but this is for the document).
The script where i need to show a 'last updated on' time is for an jquery ajax script, which updates a certain piece of code every ... seconds/minutes.
function getPastTimestamp(t) {
var d = new Date(t);
var output = "";
var items = new Array();
var i = 0;
items[i++] = d.getMonth() + 1;
items[i++] = d.getDate();
items[i++] = d.getFullYear();
items[i++] = d.getHours();
items[i++] = d.getMinutes();
items[i] = d.getSeconds();
for (i = 0; i < items.length; i += 1) {
output += (items[i] < 10) ? "0" + items[i] : items[i];
if (i < items.length - 1) output += '/';
}
return output;
}
function getCurrentTimestamp() {
return getPastTimestamp((new Date()).getTime());
}

Categories