Getting the current date and time and appending it to a string - javascript

I need to create strings in javascript that contain the current time.
How can I create two strings like the following, but with the current timestamp?
itemTimestamp = "Itemized at 2014-05-01, 11:11 PM"
itemFilename = "itemized_at_2014_05_01_11_11_pm.png"

JSFIDDLE:
http://jsfiddle.net/gkQ7y/9/
function format(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
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'
hours = hours < 10 ? '0' + hours : hours; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime ="Itemized at "+year+"-"+month+"-"+day+", "+hours + ':' + minutes + ' ' + ampm;
return strTime;
}
var d = new Date();
document.getElementById("test1").innerHTML = format(d);
var replaced = format(d).replace(/[ :-]/g,"_").replace(",","");
document.getElementById("test2").innerHTML = replaced+".png";

Related

display current dates hours and minute

I am facing an issue in javascript dates. i want to do minutes and second from current date.
My code:
date = new Date();
currentdate = new Date();
newCurrent = GetFormattedDate(currentdate);
GetFormattedDate(date) {
hour = ("0" + (date.getHours())).slice(-2);
min = ("0" + (date.getMinutes())).slice(-2);
return hour + ":" + min; //output 18:43
}
expected output:
`18:00` //if minutes are 0 to 29 then show current hours reset the minutes again start with 0 like 18:00
`18:30` //if minutes are 29 to 59 then show current hours reset the minutes again start with 30 like 18:30
What should I do? anyone help me?
var d = new Date();
var myTime = d.getHours() +':'+ (d.getMinutes() <= 29 ? '00' : '30') ;
template string:
const d = new Date();
const myTime = `${d.getHours()}:${d.getMinutes() <= 29 ? '00' : '30'}` ;
or
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var altedMinutes = minutes <= 29 ? '00' : '30';
var displayTime = hours + ':' + altedMinutes;
If you want PM/AM
var suffix = 'AM'
var hours = now.getHours()
if (hours>11) {
hours - =12;
suffix = 'PM'
}
...
var displayTime = hours + ':' + altedMinutes + ' ' + suffix;

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

Javascript: Formatting datetime yields NaN results

I am trying to format a mysql datetime object in Javascript, but I only get NaN results.
The value from the database is for example this datetime object:
2015-08-27 21:36:03
In my JS I try to convert this object as follows:
var formattedDate = new Date(datetimeObj);
function formatDate(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes;
return date.getMonth()+1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
How come that I when printing the variable, I get NaN/NaN/NaN 12:NaN?
Some browsers will not parse the string "2015-08-27 21:36:03" as a valid date. For best results, use a standard ISO date string, as in
2015-08-27T21:36:03Z
Try this:
<script>
var formattedDate = new Date("2015-08-27 21:36:03");
console.log(formatDate(formattedDate));
function formatDate(date)
{
var hours = date.getHours();
var minutes = date.getMinutes();
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0' + minutes : minutes;
var strTime = hours + ':' + minutes;
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
</script>
Its the same code, just passed the input in your function..
Here you can find answer on your quetions, it something like this with RegEx
var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateObject = new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);

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