Adjusting JavaScript Date and Time [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Formatting a date in JavaScript
How to get datetime in javascript?
I've found a script that displays the current date and time in various time zones. I can't figure out how to change the format. Currently, it displays as MM/DD/YYYY HH:MM:SS AM/PM and I want it to just display as HH:MM AM/PM
I'm more skilled with jQuery than plain JavaScript, and this is confounding me:
$(document).ready(function() {
function calcTime(offset) {
currentDate = new Date();
utc = currentDate.getTime() + (currentDate.getTimezoneOffset() * 60000);
newDate = new Date(utc + (3600000*offset));
return newDate.toLocaleString();
}
function displayTimes() {
$("#chicago").html(calcTime("-6"));
$("#london").html(calcTime("+1"));
$("#shanghai").html(calcTime("+8"));
};
window.setInterval(displayTimes, 1000);
});

The culprit is the following line.
return newDate.toLocaleString();
Specifically, toLocaleString()
You can find out more about what that line's doing here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
A quick way would be to use .toTimeString()
Instead of returning newDate.toLocaleString() or .toTimeString() you want to make it print as you wish it to.
e.g.
return newDate.getHours() + ':' newDate.getMinutes();
That'll give you the military time.
If you want am/pm display, this can get that for you
(newDate.getHours() > 11) ? 'pm' : 'am'
If you want the time prettified, 0 is 12 midnight, and 12 is noon. You can subtract 12 if the hours are greater than 12. If 0, you can also set it to display 12. All that can be done like this:
(newDate.getHours() === 0) ? 12 : ((newDate.getHours() > 12) ? newDate.getHours() - 12 : newDate.getHours());
Should definitely use a var for newDate.getHours(). Speaking of vars...
Please reformat your vars as such:
var currentDate = new Date(),
utc = currentDate.getTime() + (currentDate.getTimezoneOffset() * 60000),
newDate = new Date(utc + (3600000*offset));
Hope that helps.
EDIT: All together now:
replace the following
return newDate.toLocaleString();
with the following
return (newDate.getHours() === 0) ? 12 : ((newDate.getHours() > 12) ? newDate.getHours() - 12 : newDate.getHours()) + ' : ' + newDate.getMinutes() + ' ' + (newDate.getHours() > 11) ? 'pm' : 'am';
That's rather sloppy, and hurriedly written, but if you use a var for newDate.getHours() it'll be an easier read.
Thanks.

var myDate= new Date();
myDate.format("h:mm tt");
http://www.jslab.dk/library/date.format

Related

Display time based on my Operating System time format

I am new to coding. I know HTML, CSS, and js. My question is I want to display time in my HTML page based on Operating system time format. For example, my system time format is 12 hours format I need to show 12 hours format if my system time format is 24 hours I need to show 24 hours format in my HTML page. I test myself switch time format in OS time settings. That time also page time has to change.
Is it possible to do with HTML, CSS and js?
If not is there any alternative ways to do it. Help or suggest me
it may help
var currentTime = new Date(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes();
if (minutes < 10) {
minutes = "0" + minutes;
}
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
document.write(hours + ":" + minutes + " " + suffix)
Short answer is No, but, You can check how the system query possibilities used:
console.log(navigator)
Check this answer
Get system infos with JS Answer &
Navigator documentation
not sure if we've a function to differentiate the time format and give us output based on OS time. But just in case if you've a chance to manipulate at your end, try this using JavaScript built-in functions :
For 12-hr Format :
let formattedTime = new Date().toLocaleTimeString('en-US');
console.log(formattedTime)
For 24-hr Format :
let currentDateTime = new Date();
let formattedTime = currentDateTime.getHours() + ":" + currentDateTime.getMinutes() +":" + currentDateTime.getSeconds();
console.log(formattedTime)
(Or)
For 24-hr Format in one line as #Edson stated :
let currentDateTime = new Date();
console.log(currentDateTime.toLocaleTimeString('en-US', { hour12: false }))

Date/Time format in Javascript

I have a time string which is 01:00:00 all I want to do is convert it to 1:00 am using Javascript date time conversion.
I have tried SimpleDateFormat which gives SimpleDateFormat is not defined
Following are the links i found but could not understand or implement:
This gives Invalid Date
This gives SimpleDateFormat is not defined
This gives the same.
I just want to understand how date and time formatting works in Javascript.
I already do it in java with SimpleDateFormat, but i think it is not as easy in JS.
Please help. Thanks in Advance.
EDIT:
This link was suggested as a possible duplicate, but then the function in that answer accepts Date object. I want to convert string time to Date.
Try this , just use date object and extract hours and minutes , i think is easy to understand it
vvar str = "01:00:00"; var res = str.split(":");
document.getElementById("demo").innerHTML = res[0]; // =01
document.getElementById("demo").innerHTML = res[1]; // =00
document.getElementById("demo").innerHTML = res[2]; // =00
so in your case , should be :
var str = "01:00:00";
var res = str.split(":");
var hour = res[0]; // =01
var minutes=res[1]; // = 00
var ampm = hour >= 12 ? 'PM' : 'AM';
hour = hour % 12;
hour = hour ? hour : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? minutes : minutes;
var strTime = hour + ':' + minutes + ' ' + ampm;
alert(strTime);
ps. if u wanna use java , you can do it in a jsp page where you can use java , html and javascript .

Convert my my variable into a 12/12 time format using moment.js

I need to convert my time that is in military time 24 hours time to regular 12/12 time.
nextArrivalFinal2 = ((hour > 0 ? hour + ":" + (min < 10 ? "0" : "") : "") + min + ":" + (sec < 10 ? "0" : "") + sec);
console.log("nextArrival2", typeof nextArrivalFinal2)
console.log("nextArrival2", nextArrivalFinal2)
var convertedDate = moment(new Date(nextArrivalFinal2));
console.log('converted1', convertedDate)
console.log('converted', moment(convertedDate).format("hh:mm:ss"));
nextArrivalFinal2 displays the time as a string in HH:MM:ss format. But when I plug it into the moment js, it says it is an invalid date.
You are not parsing the time with moment.js, the line:
var convertedDate = moment(new Date(nextArrivalFinal2));
is using the date constructor to parse a string like "13:33:12", which will likely return an invalid date in every implementation (and if it doesn't, it will return something that may be very different to what you expect).
Use moment.js to parse the string and tell it the format, e.g.
var convertedDate = moment(nextArrivalFinal2, 'H:mm:ss'));
Now you can get just the time as:
convertedDate().format('h:mm:ss a');
However, if all you want is 24 hr time reformatted as 12 hour time, you just need a simple function:
// 13:33:12
/* Convert a time string in 24 hour format to
** 12 hour format
** #param {string} time - e.g. 13:33:12
** #returns {sgtring} same time in 12 hour format, e.g. 1:33:12pm
*/
function to12hour(time) {
var b = time.split(':');
return ((b[0]%12) || 12) + ':' + b[1] + ':' + b[2] + (b[0] > 12? 'pm' : 'am');
}
['13:33:12','02:15:21'].forEach(function(time) {
console.log(time + ' => ' + to12hour(time));
});

Javascript format date / time [duplicate]

This question already has answers here:
Formatting the date time with Javascript
(12 answers)
Closed 8 years ago.
I need to change a date/time from 2014-08-20 15:30:00 to look like 08/20/2014 3:30 pm
Can this be done using javascript's Date object?
Yes, you can use the native javascript Date() object and its methods.
For instance you can create a function like:
function formatDate(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;
return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + " " + strTime;
}
var d = new Date();
var e = formatDate(d);
alert(e);
And display also the am / pm and the correct time.
Remember to use getFullYear() method and not getYear() because it has been deprecated.
DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/
Please do not reinvent the wheel. There are many open-source and COTS solutions that already exist to solve this problem.
Please take a look at the following JavaScript libraries:
Luxon: [CDN] | [Source] | [Minified]
Moment.js: [CDN] | [Source] | [Minified]
Datejs: [CDN] | [Source] | [Alpha1.zip (1.6MB)]
Demo
Update: I wrote a one-liner using Moment.js Luxon below.
const { DateTime } = luxon;
const value = DateTime
.fromFormat("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
.toFormat('MM/dd/yyyy h:mm a');
console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>
Here is the original version using Moment. Since Luxon is the successor to Moment, I have included this as an alternative.
const value = moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a');
console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
For the date part:(month is 0-indexed while days are 1-indexed)
var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' + date.getFullYear());
for the time you'll want to create a function to test different situations and convert.
I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.
function formatDate(date) {
var year = date.getFullYear(),
month = date.getMonth() + 1, // months are zero indexed
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
minuteFormatted = minute < 10 ? "0" + minute : minute,
morning = hour < 12 ? "am" : "pm";
return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
minuteFormatted + morning;
}
You can do that:
function formatAMPM(date) { // This is to display 12 hour format like you asked
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;
return strTime;
}
var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);
Fiddle

jQuery Format Time

I have a jQuery script that receives a string in milliseconds inside a parameter, like this:
params.tweetDate='77771564221';
What I need to do is to create a jQuery function that will be able to format this milliseconds string in a USA time, like 10.00 AM or 10.00 PM.
Is there a jQuery function that is able to do this?
Please help.
Thanks
There is Date object in pure javascript, no jQuery needed.
http://www.javascriptkit.com/jsref/date.shtml
Example:
var time = new Date(params.tweetDate),
h = time.getHours(), // 0-24 format
m = time.getMinutes();
// next just convert to AM/PM format (check if h > 12)
No, there's no jQuery function for this. You can use
JavaScript's own Date object, using the getHours() and getMinutes() functions, handling the AM/PM thing yourself (e.g., hours >= 12 is PM), padding out the minutes with a leading 0 if minutes is less than 10, etc. Also note that if hours is 0, you want to make it 12 (because when using the AM/PM style, you write midnight as "12:00 AM", not "0:00 AM").
DateJS, an add-on library that does a huge amount of date stuff (although sadly it's not actively maintained)
PrettyDate from John Resig (the creator of jQuery)
To use just about any of those, first you have to turn that "milliseconds" value into a Date object. If it's really a "milliseconds" value, then first you parse the string into a number via parseInt(str, 10) and then use new Date(num) to create the Date object representing that point in time. So:
var dt = new Date (parseInt(params.tweetDate, 10));
However, the value you've quoted, which you said is a milliseconds value, seems a bit odd — normally it's milliseconds since The Epoch (Jan 1, 1970), which is what JavaScript uses, but new Date(parseInt("77771564221", 10)) gives us a date in June 1972, long before Twitter. It's not seconds since The Epoch either (a fairly common Unix convention), because new Date(parseInt("77771564221", 10) * 1000) gives us a date in June 4434. So the first thing to find out is what that value actually represents, milliseconds since when. Then adjust it so it's milliseconds since The Epoch, and feed it into new Date() to get the object.
Here is a function for you:
function timeFormatter(dateTime){
var date = new Date(dateTime);
if (date.getHours()>=12){
var hour = parseInt(date.getHours()) - 12;
var amPm = "PM";
} else {
var hour = date.getHours();
var amPm = "AM";
}
var time = hour + ":" + date.getMinutes() + " " + amPm;
console.log(time);
return time;
}
You may call the function in any approach like:
var time = timeFormatter(parseInt("2345678998765"));
take a look at timeago: this is a jquery plugin used exactly for this purposes.
Using T.J.'s solution this is what I ended up with.
var date = new Date(parseInt("77771564221", 10));
var result = new Array();
result[0] = $.datepicker.formatDate('DD, M, d, yy', date);
result[1] = ' ';
if (date.getHours() > 12) {
result[2] = date.getHours() - 12;
} else if (date.getHours() == 0 ) {
result[2] = "12";
} else {
result[2] = date.getHours();
}
result[3] = ":"
result[4] = date.getMinutes();
if (date.getHours() > 12) {
result[5] = " pm";
} else {
result[5] = " am";
}
console.log(result.join(''));

Categories

Resources