I need your help
If the code below is able to get the date in my requested format of: dd/mm/yyyy
How do I go about getting the time in a 12hr format ie. 13:53 is 1:53pm
Thank you
<script type="text/javascript">
function test() {
var d = new Date(),
m = d.getMonth() + 1,
xdate = [d.getDate(), (m < 10) ? '0' + m : m, d.getFullYear()].join('/');
var t = d.format("h:mm ss");
alert("the date is:" + xdate + "time is:" + t)
}
</script>
Demo jsFiddle
JS
var d = new Date();
alert("the date is: " + d.toLocaleDateString() + "time is: " + d.toLocaleTimeString());
Note: these functions aren't exactly cross browser supported
Use this:
var d = new Date(),
m = d.getMonth()+1,
x = [d.getDate(), (m < 10) ? '0' + m : m, d.getFullYear()].join('/'),
y = d.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
alert(x +" "+ y)
Taken from:
How do you display javascript datetime in 12 hour AM/PM format?
It is not that difficult. Try this one out :
JS:
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");
}
return formatted;
}
})();
console.log(formatTime(new Date()));
Find the working fiddle here : http://jsfiddle.net/rRd2P/1/
Related
"2015-06-23 14:00:00"
I tried to format above date time into 12 hour base but stuck in somewhere.
function formatDate(raw_date){
var right = raw_date.substring(10, 0);
var hours = ((right[0].substring(2,0) + 11) % 12 + 1);
var min = raw_date.substring(14,16);
var suffix = right[1] >= 12 ? "PM":"AM";
right[1] = ((right[1] + 11) % 12 + 1) + suffix;
return hours + ':' + min + ' ' + suffix;
}
Can someone help? My desired output is "23/06/2015 02:00 PM"
Try this:
function formatDate(raw_date) {
var right = new Date(raw_date);
var currentHours = right.getHours();
var timeOfDay = (currentHours < 12) ? "AM" : "PM";
if (currentHours > 12) {
currentHours -= 12;
}
return (right.getDate() + '/' + right.getMonth()+ '/' + right.getFullYear() +" "+ currentHours+ ":"+right.getMinutes() + timeOfDay);
}
alert(formatDate("2015-06-23 14:00:00"));
Demo
Solution based on your code:
function formatDate(raw_date){
var year = raw_date.substring(0,4);
var month = raw_date.substring(5,7);
var day = raw_date.substring(8,10);
var right = raw_date.substring(10);
var hours = ((right.substring(0,3))% 12 );
var min = raw_date.substring(14,16);
var suffix = right.substring(0,3) >= 12 ? "PM":"AM";
return day + "/"+month+"/"+year+" "+hours + ':' + min + ' ' + suffix;
}
You should follow a simple flow.
Try to break down the input -> convert them _> and then sum them up:
function formatDate(raw_date){
var right = raw_date.substring(0, 10);
var year=right.substring(0,4);
var month=right.substring(5,7);
var day=right.substring(8,10);
right=day+"/"+month+"/"+year;
var left=raw_date.substring(11, raw_date.length);
var hours = left.substring(0,2);
var suffix = hours >= 12 ? "PM":"AM";
hours=hours-12;
if(hours<10) hours='0'+hours;
var min = left.substring(3,5);
left=hours+":"+min+" "+suffix;
return right + ' ' + left;
}
I am trying to get Days,hours from two dates.I searched for the solution and try some code like below but none of them returns the correct days with hours like 2 days ,3 hours.My fields values are like :
d1 = '2014-10-09 08:10:56';
d2 ='2014-11-09 10:10:56';
var dateDiff = function ( d1, d2 ) {
var diff = Math.abs(d1 - d2);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000) + " days";
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000) + " hours";
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000) + " minutes";
} else {
return "< 1 minute";
}
};
function DateDiff(date1, date2) {
var msMinute = 60*1000,
msDay = 60*60*24*1000,
c = new Date(), /* now */
d = new Date(c.getTime() + msDay - msMinute);
return Math.floor(((date2 - date1) % msDay) / msMinute) + ' full minutes between'; //Convert values days and return value
}
what am i doing wrong.Any help thanks
Have you converted d1, d2 to Date object before calling the function dateDiff? Because if you haven't, this line var diff = Math.abs(d1 - d2); won't work as expected.
UPDATE:
I'am assuming your d1 and d2 are in "Y-m-d H:S:M" format, try this:
function parseDate(str){
var tmp = str.split(' ');
var d = tmp[0].split('-');
var t = tmp[1].split(':');
return new Date(d[0], d[1]-1, d[2], t[0], t[1], t[2]);
}
function dateDiff(d1, d2){
d1 = parseDate(d1);
d2 = parseDate(d2);
// ...
// Your code continues
}
I wish I could make it simpler... But this seems to work.
var d1 = '2014-10-09 08:10:58',
d2 ='2015-10-09 08:10:50';
function getDateFromString(str) {
var regexDate = /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/,
values = regexDate.exec(str);
return new Date(values[1], values[2], values[3], values[4], values[5], values[6]);
}
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
function dateDiff(d1,d2){
if (d1.getTime() > d2.getTime()) {
var oldD1 = d1;
d1 = d2;
d2 = oldD1;
}
var yearDiff = d2.getFullYear() - d1.getFullYear(),
monthDiff = d2.getMonth() - d1.getMonth(),
dayDiff = d2.getDate() - d1.getDate(),
hourDiff = d2.getHours() - d1.getHours(),
minDiff = d2.getMinutes() - d1.getMinutes(),
secDiff = d2.getSeconds() - d1.getSeconds();
if (secDiff < 0) {
secDiff = 60 + secDiff;
minDiff--;
}
if (minDiff < 0) {
minDiff = 60 + minDiff;
hourDiff--;
}
if (hourDiff < 0) {
hourDiff = 24 + hourDiff;
dayDiff--;
}
if (dayDiff < 0) {
var days = daysInMonth(date2.getMonth(), date2.getFullYear());
dayDiff = days + dayDiff;
monthDiff--;
}
if (monthDiff < 0) {
monthDiff = 12 + monthDiff;
yearDiff--;
}
var diff = yearDiff > 0 ? yearDiff + " years " : "";
diff += monthDiff > 0 ? monthDiff + " months " : "";
diff += dayDiff > 0 ? dayDiff + " days " : "";
diff += hourDiff > 0 ? hourDiff + " hours " : "";
diff += minDiff > 0 ? minDiff + " minutes " : "";
diff += secDiff > 0 ? secDiff + " seconds " : "";
return diff;
}
var date1 = getDateFromString(d1),
date2 = getDateFromString(d2)
document.getElementById('test').innerHTML += date1 + "<br />" + date2;
document.getElementById('test').innerHTML += "<br />" + dateDiff(date1, date2);
console.log(dateDiff(date1, date2));
See JSFiddle
It works in all browsers.
Try this - >
d1 = '2014-10-09 08:10:56';
d2 = '2014-11-09 10:10:56';
var diff = dateDiff(d1,d2);
alert(diff);
function splitDate(d1){
var dSplit = d1.split(' ');
d = dSplit[0] + 'T' + dSplit[1];
return d;
}
function dateDiff(d1,d2){
d1 = splitDate(d1);
d2 = splitDate(d2);
var date1 = new Date(d1);
var date2 = new Date(d2);
var dateDiff = new Date(date2 - date1);
var diff = "Month " + dateDiff.getMonth() + ", Days " + dateDiff.getDay() + ", Hours " + dateDiff.getHours();
return diff;
}
I am assuming you want the difference between 2 dates.
var dateDiff = function(d1/*String*/, d2/*String*/){
var date1 = new Date(d1);
var date2 = new Date(d2);
var result = {
negative:false
};
var diff = date1-date2;
if(diff<0){
result.negative = true;
diff*=-1;
}
result.milliseconds = diff%1000;
diff-=result.milliseconds;
diff/=1000;
result.seconds = diff%60;
diff-=result.seconds
diff/=60;
result.minutes = diff%60;
diff-=result.minutes
diff/=60;
result.hours = diff%24;
diff-=result.hours
result.days= diff/=24;
//And so on
return result;
}
I'm not sure if I really understood but I think this is what you want : http://jsfiddle.net/OxyDesign/927n0L34/
JS
var difference = toDaysAndHours('2014-10-09 08:10:56','2014-11-09 10:10:56');
function toDaysAndHours(d1,d2){
var dif, hours, days, difString = '';
d1 = new Date(d1);
d2 = new Date(d2);
dif = Math.abs(d1 - d2);
hours = (dif/(1000*60*60)).toFixed(0);
days = (hours/24).toFixed(0);
hours = hours - days*24;
difString = days+' days, '+hours+' hours';
return difString;
}
In the first function you are using strings not dates. to properly initialize a date use the constructor, as in:
d1 = new Date('2014-10-09 08:10:56')
d2 = new Date('2014-11-09 10:10:56')
Then on d1 and d2 you can use all of the get*/set* methods specified here: http://www.w3schools.com/jsref/jsref_obj_date.asp
While I got distracted writing the answer, I see others have said similar things, but I will add this:
The data object approach is good for understanding things, but if you want to save time use http://momentjs.com/ or a similar module to save time and mistakes.
This question already has answers here:
How do you display JavaScript datetime in 12 hour AM/PM format?
(31 answers)
Closed 8 years ago.
Currently shows the time in a 24 Hour clock format. Can this be chnaged to show a 12 Hour clock with AM or PM? Thanks
function startTime() {
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
Yes, if you want to continue formatting manually, you can use something like this:
element.innerHTML = (h > 12 ? h - 12 : h) + ":" + m + ":" + s + (h >= 12 ? " PM" : " AM");
new Date().toLocaleTimeString()
/* returned value: (String)
eg. 11:25:50 AM
or 8:08:41 PM
*/
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
var ampm = h >= 12 ? 'pm' : 'am';
h = h % 12;
h = h ? h : 12;
m = m < 10 ? '0' + m : m;
var strTime = h + ':' + m + ':' + s +' ' + ampm;
document.getElementById('txt').innerHTML = strTime;
var t = setTimeout(function () { startTime() }, 500);
}
function checkTime(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
DEMO
Im creating a JS clock/date. I previously got the time to work perfectly then I decided to add more onto my clock (date). Right now I cant figure why it isn't working. If anyone could give me tip or idea how to fix it, I would greatly appreciate it.
function timedate()
{
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var dn="PM"
var d = currentTime.getDate(); <--
var day = (d < 10) ? '0' + d : d;
var m = currentTime.getMonth() + 1; <--
var month = (m < 10) ? '0' + m : m;
var yy = currentTime.getYear(); <--
var year = (yy < 1000) ? yy + 1900 : yy;
if (hours<12)
{
dn="AM"
}
if (hours>12)
{
hours=hours-12
}
if (hours==0)
{
hours=12
}
if (minutes<=9)
{
minutes="0"+minutes
}
var clocklocation = document.getElementById('timedate');
clocklocation.innerHTML = "" +hours+":"+minutes+dn+""+day + "/" + month + "/" + year;
setTimeout("timedate()", 1000);
}
timedate();
Your code works, it is just not visible because you do not have seconds showing
Also change
setTimeout("timedate()", 1000);
to
setTimeout(timedate, 1000);
because it is not recommended
and remove the <--
Make sure it runs onload or after the tag you want to show it in
Alternatively remove the line and change
timedate();
to
setInterval(timedate,1000)
const pad = num => ("0" + num).slice(-2);
const timedate = () => {
const currentTime = new Date();
let hours = currentTime.getHours();
const minutes = pad(currentTime.getMinutes());
const seconds = pad(currentTime.getSeconds());
const d = currentTime.getDate();
const day = pad(d);
const month = pad(currentTime.getMonth() + 1);
const yy = currentTime.getFullYear();
let dn = "PM"
if (hours <= 12) dn = "AM";
if (hours >= 12) hours -= 12;
if (hours == 0) hours = 12;
hours = pad(hours);
document.getElementById('timedate').innerHTML = "" +
hours + ":" +
minutes + ":" +
seconds + dn + " " +
day + "/" + month + "/" + yy;
}
window.addEventListener("load", function() {
setInterval(timedate, 1000);
});
<span id="timedate"></span>
If you set the timeout with setTimeout(timedate, 1000) instead of your current magic string version, it works1.
1 I took the liberty of adding seconds to your code as well, to make it obvious that the clock updates. Of course, you also need to remove <-- from your code.
I have a question, how can I change time from 24hr format to 12, the easiest way, in javascript or Jquery .
This is what I have :
TempDate = $.datepicker.formatDate('MM dd, yy', TempDate);
var ChangeDate = TempDate + " " + TradeTime;
now TradeTime= 15:59 , but I wanna be 3:59PM
What is the easiest way , or can I use datapicker or to force this format in the same time with date.
Thanks
I'm afraid you will just have to do it manually, quick n dirty, for now ;)
function to12Hrs(strHrs, strMin) {
var hrs = Number(strHrs);
var min = Number(strMin);
var ampm = "am";
if(isNaN(hrs) || isNaN(min) || hrs > 23 || hrs < 0) {
throw ("Invalid Date " + str24Hrs);
}
if(hrs >= 12) {
hrs = (hrs - 12) || 12;
ampm = "pm";
}
var strHr = (hrs < 10) ? "0".concat(hrs) : hrs;
var strMin = (min < 10) ? "0".concat(min) : min;
return (strHr + ":" + strMin + ampm);
}
var arr = "12:30".split(":");
alert(to12Hrs(arr[0], arr[1])); // 12:30pm
arr = "11:00".split(":");
alert(to12Hrs(arr[0], arr[1])); // 11:00am
arr = "02:00".split(":");
alert(to12Hrs(arr[0], arr[1])); // 02:00am
arr = "20:00".split(":");
alert(to12Hrs(arr[0], arr[1])); // 08:00pm
This helped me :
TradeTime = ("" + TradeTime).split(":",2);
if (TradeTime[0] < 12)
{
a_p = "AM";
}
else
{
a_p = "PM";
}
if (TradeTime[0] == 0)
{
TradeTime[0] = 12;
}
if (TradeTime[0] > 12)
{
TradeTime[0] = TradeTime[0] - 12;
}