Date.ISOString wrongly converts from timestamp? [duplicate] - javascript

Timestamp:
1395660658
Code:
//timestamp conversion
exports.getCurrentTimeFromStamp = function(timestamp) {
var d = new Date(timestamp);
timeStampCon = d.getDate() + '/' + (d.getMonth()) + '/' + d.getFullYear() + " " + d.getHours() + ':' + d.getMinutes();
return timeStampCon;
};
This converts the time stamp properly in terms of time format, but the date is always:
17/0/1970
Why - cheers?

You have to multiply by 1000 as JavaScript counts in milliseconds since epoch (which is 01/01/1970), not seconds :
var d = new Date(timestamp*1000);
Reference

function convertTimestamp(timestamp) {
var d = new Date(timestamp * 1000), // Convert the passed timestamp to milliseconds
yyyy = d.getFullYear(),
mm = ('0' + (d.getMonth() + 1)).slice(-2), // Months are zero based. Add leading 0.
dd = ('0' + d.getDate()).slice(-2), // Add leading 0.
hh = d.getHours(),
h = hh,
min = ('0' + d.getMinutes()).slice(-2), // Add leading 0.
ampm = 'AM',
time;
if (hh > 12) {
h = hh - 12;
ampm = 'PM';
} else if (hh === 12) {
h = 12;
ampm = 'PM';
} else if (hh == 0) {
h = 12;
}
// ie: 2014-03-24, 3:00 PM
time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm;
return time;
}
You can get the value by calling like convertTimestamp('1395660658')

Because your time is in seconds. Javascript requires it to be in milliseconds since epoch. Multiply it by 1000 and it should be what you want.
//time in seconds
var timeInSeconds = ~(new Date).getTime();
//invalid time
console.log(new Date(timeInSeconds));
//valid time
console.log(new Date(timeInSeconds*1000));

const timeStamp = 1611214867768;
const dateVal = new Date(timeStamp).toLocaleDateString('en-US');
console.log(dateVal)

Related

Substract time zone from timestamp [duplicate]

This question already has answers here:
javascript toISOString() ignores timezone offset [duplicate]
(7 answers)
Parse date without timezone javascript
(16 answers)
Closed 3 years ago.
I have time that is represented in response as: 1386180000 and in javascript it adds timezone, as: Wed Dec 04 2013 19:00:00 GMT+0100 (Central European Standard Time). How to subtract timezoneOffset from date in this case?
I am using this function to format it:
convertTimestamp = timestamp => {
var d = new Date(timestamp), // Convert the passed timestamp to milliseconds
yyyy = d.getFullYear(),
mm = ("0" + (d.getMonth() + 1)).slice(-2), // Months are zero based. Add leading 0.
dd = ("0" + d.getDate()).slice(-2), // Add leading 0.
hh = d.getHours(),
h = hh,
min = ("0" + d.getMinutes()).slice(-2), // Add leading 0.
sec = ("0" + d.getSeconds()).slice(-2), // Add leading 0.
ampm = "AM",
time;
if (hh > 12) {
h = hh - 12;
ampm = "PM";
} else if (hh === 12) {
h = 12;
ampm = "PM";
} else if (hh === 0) {
h = 12;
}
// ie: 2013-02-18, 8:35 AM
// time = dd + "/" + mm + "/" + yyyy + " " + h + ":" + min + " " + ampm;
time = yyyy + "/" + mm + "/" + dd + " " + h + ":" + min + ":" + sec + " " + ampm;
return time;
};

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.

Convert integer time facebook message time - javascript

How to Covert This time to date time like " 08:45 PM "
json time code
{"time":1480797244,"short":false,"forceseconds":false}
i need covert this time (1480797244) need idea in jQuery or javascript
Use the below method to convert the timestamp to your required format. Check the Updated fiddle also
function formatAMPM(timestamp) {
date = new Date(timestamp * 1000)
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
var day = date.getDate();
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 = day + '/' + month + '/' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var timeObj = {"time":1480797244,"short":false,"forceseconds":false};
alert(formatAMPM(timeObj.time))

Add 5 minutes to current time javascript

I am getting the current date as below:
var now = new Date();
I want to add 5 minutes to the existing time. The time is in 12 hour format. If the time is 3:46 AM, then I want to get 3:51 AM.
function DateFormat(date) {
var days = date.getDate();
var year = date.getFullYear();
var month = (date.getMonth() + 1);
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 = days + '/' + month + '/' + year + '/ ' + hours + ':' + minutes + ' ' + ampm;
// var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
function OnlyTime(date) {
var days = date.getDate();
var year = date.getFullYear();
var month = (date.getMonth() + 1);
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 = days + '/' + month + '/' + year + '/ ' + hours + ':' + minutes + ' ' + ampm;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
function convertTime(time)
{
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);
}
function addMinutes(date, minutes) {
return new Date(date.getTime() + minutes * 60000);
}
function convertTime(time)
{
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
alert(sHours + ":" + sMinutes);
}
// calling way
var now = new Date();
now = DateFormat(now);
var next = addMinutes(now, 5);
next = OnlyTime(next);
var nowtime = convertTime(next);
How to add 5 minutes to the "now" variable?
Thanks
You should use getTime() method.
function AddMinutesToDate(date, minutes) {
return new Date(date.getTime() + minutes * 60000);
}
function AddMinutesToDate(date, minutes) {
return new Date(date.getTime() + minutes*60000);
}
function DateFormat(date){
var days = date.getDate();
var year = date.getFullYear();
var month = (date.getMonth()+1);
var hours = date.getHours();
var minutes = date.getMinutes();
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = days + '/' + month + '/' + year + '/ '+hours + ':' + minutes;
return strTime;
}
var now = new Date();
console.log(DateFormat(now));
var next = AddMinutesToDate(now,5);
console.log(DateFormat(next));
//Date objects really covers milliseconds since 1970, with a lot of methods
//The most direct way to add 5 minutes to a Date object on creation is to add (minutes_you_want * 60 seconds * 1000 milliseconds)
var now = new Date(Date.now() + (5 * 60 * 1000));
console.log(now, new Date());
get minutes and add 5 to it and set minutes
var s = new Date();
console.log(s)
s.setMinutes(s.getMinutes()+5);
console.log(s)
Quite easy with JS, but to add a slight bit of variety to the answers, here's a way to do it with moment.js, which is a popular library for handling dates/times:
https://jsfiddle.net/ovqqsdh1/
var now = moment();
var future = now.add(5, 'minutes');
console.log(future.format("YYYY-MM-DD hh:mm"))
Try this:
var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (5 * 60 * 1000));
I'll give a very short answer on how to add any string of the form ny:nw:nd:nh:nm:ns where n is a number to the Date object:
/**
* Adds any date string to a Date object.
* The date string can be in any format like 'ny:nw:nd:nh:nm:ns' where 'n' are
* numbers and 'y' is for 'year', etc. or, you can have 'Y' or 'Year' or
* 'YEar' etc.
* The string's delimiter can be anything you like.
*
* #param Date date The Date object
* #param string t The date string to add
* #param string delim The delimiter used inside the date string
*/
function addDate (date, t, delim) {
var delim = (delim)? delim : ':',
x = 0,
z = 0,
arr = t.split(delim);
for(var i = 0; i < arr.length; i++) {
z = parseInt(arr[i], 10);
if (z != NaN) {
var y = /^\d+?y/i.test(arr[i])? 31556926: 0; //years
var w = /^\d+?w/i.test(arr[i])? 604800: 0; //weeks
var d = /^\d+?d/i.test(arr[i])? 86400: 0; //days
var h = /^\d+?h/i.test(arr[i])? 3600: 0; //hours
var m = /^\d+?m/i.test(arr[i])? 60: 0; //minutes
var s = /^\d+?s/i.test(arr[i])? 1: 0; //seconds
x += z * (y + w + d + h + m + s);
}
}
date.setSeconds(date.getSeconds() + x);
}
Test it:
var x = new Date();
console.log(x); //before
console.log('adds 1h:6m:20s');
addDate(x, '1h:6m:20s');
console.log(x); //after
console.log('adds 13m/30s');
addDate(x, '13m/30s', '/');
console.log(x); //after
Have fun!
This function will accept ISO format and also receives minutes as parameter.
function addSomeMinutesToTime(startTime: string | Date, minutestoAdd: number): string {
const dateObj = new Date(startTime);
const newDateInNumber = dateObj.setMinutes(dateObj.getMinutes() + minutestoAdd);
const processedTime = new Date(newDateInNumber).toISOString();
console.log(processedTime)
return processedTime;
}
addSomeMinutesToTime(("2019-08-06T10:28:10.687Z"), 5)
Add minutes into js time by prototype
Date.prototype.AddMinutes = function ( minutes ) {
minutes = minutes ? minutes : 0;
this.setMinutes( this.getMinutes() + minutes );
return this;
}
let now = new Date( );
console.log(now);
now.AddMinutes( 5 );
console.log(now);

How to get AM or PM?

I have buttons with the names of big cities.
Clicking them, I want to get local time in them.
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = hours-2; //this is the distance from my local time
alert ('Toronto time: ' + hours + ' h'); //this works correctly
});
But how can I get AM or PM ?
You should just be able to check if hours is greater than 12.
var ampm = (hours >= 12) ? "PM" : "AM";
But have you considered the case where the hour is less than 2 before you subtract 2? You'd end up with a negative number for your hour.
Try below code:
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = (hours+24-2)%24;
var mid='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='pm';
}
alert ('Toronto time: ' + hours + mid);
});
You can use like this,
var dt = new Date();
var h = dt.getHours(), m = dt.getMinutes();
var _time = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
Hopes this will be better with minutes too.
const now = new Date()
.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })
.toLowerCase();
Basically you just need to put {hour12: true} and it's done.
result => now = "21:00 pm";
If hours is less than 12, it's the a.m..
var hours = new Date().getHours(), // this is local hours, may want getUTCHours()
am;
// adjust for timezone
hours = (hours + 24 - 2) % 24;
// get am/pm
am = hours < 12 ? 'a.m.' : 'p.m.';
// convert to 12-hour style
hours = (hours % 12) || 12;
Now, for me as you didn't use getUTCHours, it is currently 2 hours after
hours + ' ' + am; // "6 p.m."
very interesting post. in a function that take a date in parameter it can appear like that :
function hourwithAMPM(dateInput) {
var d = new Date(dateInput);
var ampm = (d.getHours() >= 12) ? "PM" : "AM";
var hours = (d.getHours() >= 12) ? d.getHours()-12 : d.getHours();
return hours+' : '+d.getMinutes()+' '+ampm;
}
with date.js
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>
you can write like this
new Date().toString("hh:mm tt")
cheet sheet is here format specifiers
tt is for AM/PM
Try this:
h = h > 12 ? h-12 +'PM' : h +'AM';
The best way without extensions and complex coding:
date.toLocaleString([], { hour12: true});
How do you display javascript datetime in 12 hour AM/PM format?
here is get time i use in my code
let current = new Date();
let cDate = current.getDate() + '-' + (current.getMonth() + 1) + '-' + current.getFullYear();
let hours = current.getHours();
let am_pm = (hours >= 12) ? "PM" : "AM";
if(hours >= 12){
hours -=12;
}
let cTime = hours + ":" + current.getMinutes() + ":" + current.getSeconds() +" "+ am_pm;
let dateTime = cDate + ' ' + cTime;
console.log(dateTime); // 1-3-2021 2:28:14 PM
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var timewithampm = hours + ':' + minutes + ' ' + ampm;
return timewithampm;
var dt = new Date();
var h = dt.getHours(),
m = dt.getMinutes();
var time;
if (h == 12) {
time = h + ":" + m + " PM";
} else {
time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
}
//var time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
console.log(`CURRENT TIME IS ${time}`);
This will work for everytime,
function Timer() {
var dt = new Date()
if (dt.getHours() >= 12){
ampm = "PM";
} else {
ampm = "AM";
}
if (dt.getHours() < 10) {
hour = "0" + dt.getHours();
} else {
hour = dt.getHours();
}
if (dt.getMinutes() < 10) {
minute = "0" + dt.getMinutes();
} else {
minute = dt.getMinutes();
}
if (dt.getSeconds() < 10) {
second = "0" + dt.getSeconds();
} else {
second = dt.getSeconds();
}
if (dt.getHours() > 12) {
hour = dt.getHours() - 12;
} else {
hour = dt.getHours();
}
if (hour < 10) {
hour = "0" + hour;
} else {
hour = hour;
}
document.getElementById('time').innerHTML = hour + ":" + minute + ":" + second + " " + ampm;
setTimeout("Timer()", 1000);
}
Timer()
<div id="time"></div>

Categories