Javascript: two buttons set two timestamp - javascript

I have a form, with two text input (two timestamp) as follows:
TimeStamp start []
TimeStamp end []
Both TimeStamps are to be filled automatically with two buttons:
[Set Start] and [Set End], that read the local timestamp in the form (24h):
2013-06-27 23:55
TimeStamp start is when the operator start filling the form, while
TimeStamp end is when the form ends to be filled (the delay between these events can be also of 1 hour)
The data are then processed by POST to a script PHP
How I can handle this timestamp settings on the client side (JS, JQuery?)
Thanks in advance
#manraj82
I found this JS function to get timestamp with JS
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + "
" + now.getHours() + ':' + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) :
(now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now.getSeconds()) :
(now.getSeconds())));
}
Now I have to associate it to two buttons

I didnt quite undesrtand what your question was but try this.This might not be the answer but will give you an idea
Date.prototype.addHours= function(h){
var newDateTime = new Date(this);
newDateTime.setHours(newDateTime.getHours() + h);
return newDateTime;
}
function getTimeStamp(dt) {
return (
(dt.getMonth() + 1) + '/' +
(dt.getDate()) + '/' + dt.getFullYear() +
" " +
dt.getHours() + ':' +
((dt.getMinutes() < 10) ? ("0" + dt.getMinutes()) : (dt.getMinutes())) + ':' +
((dt.getSeconds() < 10) ? ("0" + dt.getSeconds()) : (dt.getSeconds())));
}
var startDateTime = new Date(),
addHours = 10,
endDateTime = startDateTime.addHours(addHours);
console.log(getTimeStamp(startDateTime));
console.log(getTimeStamp(endDateTime));

Related

Why this code got an Uncaught TypeError

I want to get next day and format it into "yyyy-MM-dd HH:mm" format, but when I run this in chrome's console, I got an Uncaught TypeError: date.getHours is not a function, why? The nextDay variable is clearly an instance of Date.
But when I removed hour and minute, just kept year, month and date, it successed, can anyone tell me the reason?
var time = new Date().getTime();
var interval = 24 * 60 * 60 * 1000;
var nextDay = new Date(time + interval);
function padding(number) {
return number < 10 ? "0" + number : "" + number;
}
function format(date) {
var year = date.getFullYear(),
month = date.getMonth(),
date = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
console.log(format(nextDay));
Your function takes a parameter named "date" and then tries to declare a local variable named "date". That declaration will be ignored, and the initializer will just overwrite the value of the parameter.
Change the name of the parameter:
function format(d) {
var year = d.getFullYear(),
month = d.getMonth(),
date = d.getDate(),
hour = d.getHours(),
minute = d.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
You are using the same variable name as the parameter, date is used twice, change the variable name like down below.
var time = new Date().getTime();
var interval = 24 * 60 * 60 * 1000;
var nextDay = new Date(time + interval);
function padding(number) {
return number < 10 ? "0" + number : "" + number;
}
function format(date) {
var year = date.getFullYear(),
month = date.getMonth(),
theDate = date.getDate(), //change the variable name
hour = date.getHours(),
minute = date.getMinutes();
return padding(year) + "-"
+ padding(month + 1) + "-"
+ padding(date) + " "
+ padding(hour) + ":"
+ padding(minute);
}
console.log(format(nextDay));

get 24 hours date and time for loop in javascript

I have one drop-down(values are "Last 24 hours", "Last 48 hours", etc like) when I select "Last 24 hours" in the drop-down
i need all dates from now to yesterday with one hour intervals.
i tried this,
var todayDate = new Date();
if(type=="hours"){ // for hours based drop-down
var oneDayAgo = new Date(todayDate.getTime());
oneDayAgo.setDate(todayDate.getDate() - 1);
console.log("oneDayAgo"+oneDayAgo);
var hours = todayDate.getHours();
for(var i = hours; i <= hours+24; i++) {
if(i<25){
var newHours=i;
var newDates=todayDate.getFullYear() + "-" + ("00" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("00" + todayDate.getDate()).slice(-2) + " " + ("00" +newHours).slice(-2) + ":" + ("00" + todayDate.getMinutes()).slice(-2) + ":" + ("00" + todayDate.getSeconds()).slice(-2);
console.log(newDates);
}else{
var newHours=i-24;
var newDates=oneDayAgo.getFullYear() + "-" + ("00" + (oneDayAgo.getMonth() + 1)).slice(-2) + "-" + ("00" + oneDayAgo.getDate()).slice(-2) + " " + ("00" +newHours).slice(-2) + ":" + ("00" + oneDayAgo.getMinutes()).slice(-2) + ":" + ("00" + oneDayAgo.getSeconds()).slice(-2);
console.log(newDates);
}
}
}
my expected output is ,
for example current date and time is 2014-04-27 13:07 means,
output like 2014-04-27 13:07, 2014-04-27 12:07, 2014-04-27 11:07 , 2014-04-27 10:07.... 2014-04-26 13:07
please help on this. thanks
function getDateItems(hours) {
var toDate = new Date();
var fromDate = new Date();
fromDate.setTime(fromDate.getTime() - (hours * 60 * 60 * 1000));
var result = [];
while (toDate >= fromDate) {
result.push(toDate.getFullYear() + "-" + ("00" + (toDate.getMonth() + 1)).slice(-2) + "-" + ("00" + toDate.getDate()).slice(-2) + " " + ("00" + toDate.getHours()).slice(-2) + ":" + ("00" + toDate.getMinutes()).slice(-2) + ":" + ("00" + toDate.getSeconds()).slice(-2));
// consider using moment.js library to format date
toDate.setTime(toDate.getTime() - (1 * 60 * 60 * 1000));
}
return result;
}
var datesFrom24Hours = getDateItems(24);
var datesFrom48Hours = getDateItems(48);
console.log(datesFrom24Hours);
Here a working sample, which might be what you want.
//get type and hoursOption from dropdowns
var type = 'hours'
var hoursOption = 48;
var todayDate = new Date();
if(type=="hours"){ // for hours based drop-down
var hours = todayDate.getHours();
for(var i = hours; i <= hours + hoursOption; i++) {
todayDate.setHours(todayDate.getHours() - 1)
var newDates = todayDate.getFullYear() + "-" + ("00" + (todayDate.getMonth() + 1)).slice(-2) + "-" + ("00" + todayDate.getDate()).slice(-2) + " " + ("00" + todayDate.getHours()).slice(-2) + ":" + ("00" + todayDate.getMinutes()).slice(-2) + ":" + ("00" + todayDate.getSeconds()).slice(-2);
console.log(newDates);
}
}
For for-loop variable hours I added hourOption which comes from dropdown options, eg. 24, 48, 72, etc.
Inside loop you take todayDate and just add one hour less then before, so it will show hours counting backwards.
This worked for me
const start = new Date("2022-01-01T00:00:00");
const end = new Date("2022-01-01T23:00:00");
for (let current = start; current <= end; current.setHours(current.getHours() + 1)) {
console.log(current);
}

How to format database datetime in javascript?

I have a datetime value gotten from an SQLServer database table:
2016-08-16T17:00:00Z
Using javascript, I want to format the date as follow:
16/08/2016 17:00:00
I have used the code below:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
var date = new Date(value);
var returnStr = date.getDate() + "/" + date.getMonth() + 1 + "/" + date.getFullYear();
return returnStr;
} else {
return value;
}
}
The result from the sample resource is:
17/71/2016
I want your help to get the output result as: "16/08/2016 17:00:00"
If all you want to do is format it then you don't need to create an actual date object, you can do a simple string replace using a regex to grab the individual parts, as per this simple demo:
var value = "2016-08-16T17:00:00Z";
console.log(value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4"));
In the context of your function:
$scope.FormatDate = function (value) {
if (value !== null && typeof (value) !== 'undefined') {
return value.replace(/(\d{4})-(\d\d)-(\d\d)T([^Z]+)Z/,"$3/$2/$1 $4");
} else {
return value;
}
}
Another solution:
var parsed = Date.parse("2016-08-16T17:00:00Z"),
date = new Date(parsed),
day = date.getUTCDate(),
month = date.getUTCMonth() + 1,
year = date.getUTCFullYear(),
hour = date.getUTCHours(),
minute = date.getUTCMinutes(),
second = date.getUTCSeconds(),
dateStr = "";
day = day < 10 ? "0" + day : day;
month = month < 10 ? "0" + month : month;
hour = hour < 10 ? "0" + hour : hour;
minute = minute < 10 ? "0" + minute : minute;
second = second < 10 ? "0" + second : second;
dateStr = day + "/" + month + "/" + year + " " + hour + ":" + minute + ":" + second;
console.log(dateStr);
Updated: The old code may change across countries, because they have different local date/time format, so I have updated to format it explicitly.
Try this
function formatDate(date)
{
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' +seconds ;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
You can use this library to format the date as you desire with implementing some logic.
http://momentjs.com/
Just work with the function parameter value and use moment.
Example:
const date = moment("2016-08-16T17:00:00Z").date();
const month = moment("2016-08-16T17:00:00Z").month();
const hour = moment("2016-08-16T17:00:00Z").hour();
const year = moment("2016-08-16T17:00:00Z").year();
const minute = moment("2016-08-16T17:00:00Z").minute();
const sec = moment("2016-08-16T17:00:00Z").second();
// implementing some logic
console.log('' + date + '/' + month + '/' + year + ' ' + hour + ':' + minute + ':' + sec);
here is the fiddle:
https://jsfiddle.net/Refatrafi/6m4m7mp3/

Date/Time format issue with Chrome

I get the date/time value as below in JSON:
"ChangedDate":"\/Date(1349469145000)\/"
In FF and IE, I get the above date in 12 hr format (10/5/2012 - 3:32:25 PM) using the helper function below:
Handlebars.registerHelper('FormatDate', function (date) {
if (date == null)
return "";
else {
var value = new Date(parseInt(date.substr(6)));
return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + value.toLocaleTimeString();
}
});
however, in Chrome I still get the 24 hr format (10/5/2012 - 15:32:25).
How do I get the date/time value in 12 hr format in Chrome?
Use toLocaleTimeString when the intent is to display to the user a
string formatted using the regional format chosen by the user. Be
aware that this method, due to its nature, behaves differently
depending on the operating system and on the user's settings.
You may be better off changing this line:
return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + value.toLocaleTimeString();
to:
return value.getMonth() + 1 + "/" + value.getDate() + "/" + value.getFullYear() + " - " + (value.getHours() > 12 ? value.getHours() - 12 : value.getHours()) + ":" + value.getMinutes() + ":" + value.getSeconds();
Where we check to see if the hours are > 12 and if so we subtract 12 from that number.
(value.getHours() > 12 ? value.getHours() - 12 : value.getHours())
So your example 15:32:25 would be 15 - 12 = 3: 3:32:25.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getSeconds
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getMinutes
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getHours
EDIT
//set up example
var date = new Date("10/5/2012");
date.setHours(15,32,25,00);
//Get data from date
var month = date.getMonth()+1;
var day = date.getDate();
var year = date.getFullYear();
var hours = date.getHours();
var amOrPm = "AM";
if(date.getHours() > 12){
hours = date.getHours() - 12;
amOrPm = "PM";
}
var minutes = date.getMinutes();
if(minutes < 10)
minutes = "0" + minutes;
var seconds = date.getSeconds();
if(seconds < 10)
seconds = "0" + seconds;
var dateString = month + "/" + day + "/" + year + " - " + hours + ":" + minutes + ":" + seconds;
console.log(dateString);
I made this example a bit more detailed than needed, but it helps to show you what's going on. Hope it helps.
EXAMPLE
Condensed down this would look something like:
//Get data from date
var dateString = (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " - " + (date.getHours() > 12 ? date.getHours() - 12 : date.getHours())+ ":" + (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":" + (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()) + " " + (date.getHours() > 12 ? "PM" : "AM");
EXAMPLE

Get local Date string and time string

I am trying to get the LocaleDateString and the LocaleTimeString which that would be toLocaleString() but LocaleString gives you GMT+0100 (GMT Daylight Time) which I wouldn't it to be shown.
Can I use something like:
timestamp = (new Date()).toLocaleDateString()+toLocaleTimeString();
Thanks alot
You can use the local date string as is, just fiddle the hours, minutes and seconds.
This example pads single digits with leading 0's and adjusts the hours for am/pm.
function timenow() {
var now = new Date(),
ampm = 'am',
h = now.getHours(),
m = now.getMinutes(),
s = now.getSeconds();
if (h >= 12) {
if (h > 12) h -= 12;
ampm = 'pm';
}
if (m < 10) m = '0' + m;
if (s < 10) s = '0' + s;
return now.toLocaleDateString() + ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}
console.log(timenow());
If you build up the string using vanilla methods, it will do locale (and TZ) conversion automatically.
E.g.
var dNow = new Date();
var s = ( dNow.getMonth() + 1 ) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();

Categories

Resources