Get IST time in javascript - javascript

<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + "</b>")
//-->
</script>
Getting local comupter time.
I want to get IST time in javascript.

The following will allow you to convert local time to IST time:
var currentTime = new Date();
var currentOffset = currentTime.getTimezoneOffset();
var ISTOffset = 330; // IST offset UTC +5:30
var ISTTime = new Date(currentTime.getTime() + (ISTOffset + currentOffset)*60000);
// ISTTime now represents the time in IST coordinates
var hoursIST = ISTTime.getHours()
var minutesIST = ISTTime.getMinutes()
document.write("<b>" + hoursIST + ":" + minutesIST + " " + "</b>")

Related

Getting issue while calculating the time difference using JavaScript

I am facing some issue while calculating the time difference between two dates using the JavaScript. I am providing my code below.
Here I have cutoff time and dep_time value. I have to calculate today's date with dep_date and if today's date and time is before the cutoff time then it will return true otherwise false. In my case its working fine in Chrome but for same function it's not working in Firefox. I need it to work for all browsers.
function checkform() {
var dep_date = $("#dep_date1").val(); //07/27/2019
var cut_offtime = $("#cutoff_time").val(); //1
var dep_time = $("#dep_time").val(); //6:00pm
var dep_time1 = dep_time.replace(/[ap]/, " $&");
var todayDate = new Date();
var todayMonth = todayDate.getMonth() + 1;
var todayDay = todayDate.getDate();
var todayYear = todayDate.getFullYear();
if (todayDay < 10) {
todayDay = "0" + todayDay;
}
if (todayMonth < 10) {
todayMonth = "0" + todayMonth;
}
//console.log('both dates',todayMonth,todayDay,todayYear);
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
var todayToDate = Date.parse(todayDateText.replace(/-/g, " "));
console.log("both dates", dep_date, todayDateText);
if (inputToDate >= todayToDate) {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
var timeEnd = new Date(dep_date + " " + dep_time1);
var diff = (timeEnd - timeStart) / 60000; //dividing by seconds and milliseconds
var minutes = diff % 60;
var hours = (diff - minutes) / 60;
console.log("hr", hours);
if (parseInt(hours) > parseInt(cut_offtime)) {
return true;
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
} else {
alert("You should book this trip before " + cut_offtime + " hr");
return false;
}
}
Part of your issue is here:
var todayDateText = todayMonth + "-" + todayDay + "-" + todayYear;
var inputToDate = Date.parse(dep_date.replace(/\//g, " "));
The first line generates a string like "07-17-2019". The next changes it to "07 17 2019" and gives it to the built–in parser. That string is not a format supported by ECMA-262 so parsing is implementation dependent.
Chrome and Firefox return a date for 17 July 2019, Safari returns an invalid date.
It doesn't make sense to parse a string to get the values, then generate another string to be parsed by the built–in parser. Just give the first set of values directly to the Date constructor:
var inputToDate = new Date(todayYear, todayMonth - 1, todayDay);
which will work in every browser that ever supported ECMAScript.
Similarly:
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? "pm" : "am";
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? "0" + minutes : minutes;
var strTime = hours + ":" + minutes + " " + ampm;
var timeStart = new Date(todayDateText + " " + strTime);
appears to be a lengthy and brittle way to copy a date and set the seconds and milliseconds to zero. The following does exactly that in somewhat less code:
var date = new Date();
var timeStart = new Date(date);
timeStart.setMinutes(0,0);
use
var timeStart = new Date(todayDateText + " " + strTime)
Applying these changes to your code gives something like:
function parseMDY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[0]-1, b[1]);
}
function formatDate(d) {
return d.toLocaleString(undefined, {
day: 'numeric',
month: 'short',
year: 'numeric'
});
}
// Call function with values
function checkform(dep_date, cut_offtime, dep_time) {
// Helper
function z(n) {
return (n<10?'0':'') + n;
}
// Convert dep_date to Date
var depD = parseMDY(dep_date);
// Get the departure time parts
var dtBits = dep_time.toLowerCase().match(/\d+|[a-z]+/gi);
var depHr = +dtBits[0] + (dtBits[2] == 'pm'? 12 : 0);
var depMin = +dtBits[1];
// Set the cutoff date and time
var cutD = new Date(depD);
cutD.setHours(depHr, depMin, 0, 0);
// Get current date and time
var now = new Date();
// Create cutoff string
var cutHr = cutD.getHours();
var cutAP = cutHr > 11? 'pm' : 'am';
cutHr = z(cutHr % 12 || 12);
cutMin = z(cutD.getMinutes());
var cutStr = cutHr + ':' + cutMin + ' ' + cutAP;
var cutDStr = formatDate(cutD);
// If before cutoff, OK
if (now < cutD) {
alert('Book before ' + cutStr + ' on ' + cutDStr);
return true;
// If after cutoff, not OK
} else {
alert('You should have booked before ' + cutStr + ' on ' + cutDStr);
return false;
}
}
// Samples
checkform('07/27/2019','1','6:00pm');
checkform('07/17/2019','1','11:00pm');
checkform('07/07/2019','1','6:00pm');
That refactors your code somewhat, but hopefully shows how to improve it and fix the parsing errors.

Converting DateTimeOffset string value to Date object in javascript

I'm using ASP.NET and I have the following string:
2018-12-04T13:53:42.6785734+07:00
I want to convert the string to Date object and format the output string.
My goal: 04/12/2018 13:53:42
I've tried this way but it logged with the wrong result:
var dt = new Date('2018-12-04T13:53:42.6785734+07:00');
var day = dt.getDay(),
month = dt.getMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds();
// 2/11/2018 13:53:42
console.log(day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
var dt = new Date('2018-12-04T13:53:42.6785734+07:00');
var day = dt.getDate(),
month = dt.getMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds();
// 2/11/2018 13:53:42
console.log(day + '/' + (month + 1) + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
I changed your code like this, try:
var dt = new Date('2018-12-04T13:53:42.6785734+07:00');
var day = dt.getDate(),
month = dt.getMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds();
console.log(day + '/' + (month + 1) + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
Would it be acceptable to just manipulate the original string directly without converting to a date object like so? I can really tell what the test cases would be but assuming that the hour number is the same length (04,12) I think the following code should work.
let dt = '2018-12-04T13:53:42.6785734+07:00';
let dArr = dt.substr(0,10).split('-');
let year = dArr[0];
let month = dArr[1];
let day = dArr[2];
let time = dt.substr(11,8);
let str = month+'/'+day+'/'+year+' '+time;
console.log(str)
The following are arrays starting at 0
getDay() Get the weekday as a number (0-6)
getDate() Get the day as a number (1-31)
getMonth() Get the month as a number (0-11)
var dt = new Date("2018-12-04T13:53:42.6785734+07:00");
var day = returnDay(),
month = returnMonth(),
year = dt.getFullYear(),
hours = dt.getHours(),
minutes = dt.getMinutes(),
seconds = dt.getSeconds(),
function returnDay(){
var d = (dt.getDate() < 10) ? "0" + (dt.getDate()): dt.getDate();
return d;
}
function returnMonth(){
var m = (dt.getMonth() + 1 < 10) ? "0" + (dt.getMonth()+ 1):dt.getMonth()+ 1;
return m;
}
//04/12/2018 8:53:42
console.log(day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ':' + seconds);
see for more info:
https://www.w3schools.com/js/js_date_methods.asp
Slice it, I have used jQuery in the example because I have used in in another project and this code was just a part of a component, but it should not matter much
var getTimeOnly = new Date().getTime();
var fullDate = new Date($.now()).toString();
var datePartialTime = fullDate.slice(16, 25);
var datePartialDate = fullDate.slice(0, 16);
$('a').html( "on " + datePartialDate + 'at ' + datePartialTime);
Link to pen
https://codepen.io/damPop/pen/zMzBGN

JavaScript/jQuery: Subtract hours and minutes [duplicate]

This question already has answers here:
how to convert the minutes into hours and minutes with subtracted time(subtracted time values)
(4 answers)
Closed 4 years ago.
What I have:
Three time inputs consisting of a start time, end time and the difference between the two.
<input type="time" name="starttime" id="starttime">
<input type="time" name="endtime" id="endtime">
<input type="time" name="duration" id="duration" disabled>
What I need:
When the start or end time changes, the difference shows in the third input.
e.g. 23:15 - 20:00 = 03:15.
What I've tried:
So far, I can only produce the correct hours but not the minutes.
<script>
jQuery(document).ready(function($) {
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
// Attempt 1: Only gets hours.
//var difference_as_hours = difference / 60 / 60 / 1000;
//alert("Hour Difference: " + difference_as_hours);
// Attempt 2: Nothing happens.
//var difference_as_hours_and_minutes = difference.getHours() + ":" + difference.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_and_minutes);
// Attempt 3: Nothing happens.
//var difference_as_date = new Date("01/01/2007 " + difference);
//var difference_as_hours_and_minutes = difference_as_date.getHours() + ":" + difference_as_date.getMinutes();
//alert("Hour And Minutes Difference: " + difference_as_hours_minutes);
// Attempt 4: Nothing happens.
var formatted_time = time_format(difference);
alert(formatted_time);
}
$("#starttime, #endtime").change(calculateTime);
calculateTime();
});
function time_format(d) {
hours = format_two_digits(d.getHours());
minutes = format_two_digits(d.getMinutes());
seconds = format_two_digits(d.getSeconds());
return hours + ":" + minutes + ":" + seconds;
}
function format_two_digits(n) {
return n < 10 ? "0" + n : n;
}
</script>
How can I produce the hours and minutes?
Check below working Demo using momentjs:
let valuestart = moment.duration("20:00", "HH:mm");
let valuestop = moment.duration("23:15", "HH:mm");
let difference = valuestop.subtract(valuestart);
console.log(difference.hours() + ":" + difference.minutes())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
You try
function calculateTime() {
// Get values.
var valuestart = $("#starttime").val();
var valuestop = $("#endtime").val();
// Create date format.
var timeStart = new Date("01/01/2007 " + valuestart);
var timeEnd = new Date("01/01/2007 " + valuestop);
// Subtract.
var difference = timeEnd - timeStart;
var time = msToTime(difference);
console.log(time);
}
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
$("#starttime, #endtime").change(calculateTime);

Adding one minute to current time in Javascript

I use Date object to create time in my Javascript code and it should be formated like so : 08:04:21. This is how I tried to do it:
$('#time').click(function(){
var currentTime = new Date();
var Time=currentTime.getHours() + ":"
+ currentTime.getMinutes() + ":"
+ currentTime.setSeconds(currentTime.getSeconds() + 60);
console.log(Time);
$(this).val(Time);
});
But when Time is logged in console string looks like this 8:1:1467844916075. Same happens when i try this:
var Time=currentTime.getHours() + ":"
+ currentTime.setMinutes(currentTime.getMinutes() + 1) + ":"
+ currentTime.getSeconds();
It bring out similar result : 8:1467844916075:3. I even tried this answer: javascript add one minute to time object
$('#time').click(function(){
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
$(this).val(Time);
});
But Time in this case looks like this: 1467785566719. Any idea how to get human readable current time(not date) plus one minute?
You can check this:
Date.getTime() returns you the number of milliseconds since 1970/01/01.
So just grab it and add 1 minute to it to form new milliseconds count for new date.
var d = new Date();
var millisecondssince1970 = d.getTime();
var newMillisec = millisecondssince1970 + (1000 * 60);
var newDate = new Date(newMillisec);
console.log(newDate.getHours() + ":"
+ newDate.getMinutes() + ":"
+ newDate.getSeconds());
Please try this,
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
var date = new Date(Time);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);
Here is working example https://jsfiddle.net/oa7j3krs/2/
$('#time').click(function(){
var d = new Date($.now()+60*1000); // current time + 60s
$(this).val(d.getHours()+':'+d.getMinutes()+':'+d.getSeconds());
});
Anyway, I found a way to do this. Maybe it's not the best but it will do the job.
$('#time').click(function(){
var currentTime = new Date();
var addOneMinute = currentTime.getMinutes();
addOneMinute=parseInt(addOneMinute) + 1;
var Time=currentTime.getHours() + ":"
+ addOneMinute + ":"
+ currentTime.getSeconds();
console.log(Time);
$(this).val(Time);
});

SetTimeout is returing wrong value

function updateTime() {
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var d = day + "-" + month + "-" + year;
var hours = currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours();
var minutes = currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes();
var seconds = currentDate.getSeconds() < 10 ? "0" + currentDate.getSeconds() : currentDate.getSeconds();
var t = hours + " " + minutes + " " + seconds;
var x = d + " " + t;
return x;
}
console.log(updateTime());
var timerId = setTimeout(updateTime(), 1000);
alert(timerId);
Am trying to do a javascript timer. Here UpdateTime function is working properly. Its returing the exact result. But time is constantly being displayed. It should change according to the system time. Hence am using the setTimeout function. But its not returing the proper value. Can anyone help me out here please?
You should remove the alert and () from setTimeout's callback function,
Your code should be
function updateTime() {
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var d = day + "-" + month + "-" + year;
var hours = currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours();
var minutes = currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes();
var seconds = currentDate.getSeconds() < 10 ? "0" + currentDate.getSeconds() : currentDate.getSeconds();
var t = hours + " " + minutes + " " + seconds;
var x = d + " " + t;
return x;
}
setTimeout(updateTime, 1000);
timer in javascript with current date
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer ,1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
what would you do ?
I just edit Your code hope it will help you
function updateTime() {
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var d = day + "-" + month + "-" + year;
var hours = currentDate.getHours() < 10 ? "0" + currentDate.getHours() : currentDate.getHours();
var minutes = currentDate.getMinutes() < 10 ? "0" + currentDate.getMinutes() : currentDate.getMinutes();
var seconds = currentDate.getSeconds() < 10 ? "0" + currentDate.getSeconds() : currentDate.getSeconds();
var t = hours + " " + minutes + " " + seconds;
var x = d + " " + t;
alert(x);/*display time */
}
setTimeout(updateTime, 1000);/* just remove () braces from your code */

Categories