Display time based on my Operating System time format - javascript

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

Related

ls there a native way to create a time string?

I modified the code below to create a time string which looks exactly the way I want it. It is how my Timex watch displays time.
Is there a native way to do this? I feel like I must have re-invented the wheel as surely many have needed this method before me.
const api = {};
// gets a time string which is human readable using the Date object
api.getTime = function() {
const date = new Date();
// get minutes and add a 0 if needed
let min = date.getMinutes();
min = (parseInt(min, 10) < 10 ? '0' : '') + min;
// get hours, determine AM or PM and change to 12 hours
// not preceding 0 is needed
let hour = date.getHours();
const amPm = hour >= 12 ? 'PM' : 'AM';
hour = ( hour % 12 ) || 12;
// get seconds and add a 0 if needed
let sec = date.getSeconds();
sec = (parseInt(sec, 10) < 10 ? '0' : '') + sec;
return `${hour}:${min}:${sec} ${amPm}`;
}
module.exports = api;
I think it is definitely helping if you take a look at toLocaleTimeString(), from the documentation:
Return the time portion of a Date object as a string, using locale conventions.
You can test out this function as the following:
const date = new Date().toLocaleTimeString();
console.log(date);
I hope that helps!

convert ionic datetime to hour and min

I am using ionic date time component as below
<ion-item >
<ion-label>Time:</ion-label>
<ion-datetime displayFormat="h:mm A" pickerFormat="h mm A" [(ngModel)]="localEstDelTime"></ion-datetime>
</ion-item>
on ionViewDidLoad i am setting the value of localEstDelTime as:
var d = new Date()
var dt = d.setTime(d.getTime() + (5.5 + 2)*60*60*1000)
this.localEstDelTime = dt.toISOString()
basically 5.5 hours has been added to make it for indian time zone which is GMT + 5.5 and for this use case the time is supposed to be shown plus 2 hours of current time.
now, the requirement is let's say end user added another extra hour through UI then i want to get that hour and time in the local time zone. My code does not work properly as below:
var storeEstDelTime = Date.parse(this.localEstDelTime)
var date = new Date(storeEstDelTime)
var hours = date.getHours() + 5.5
var minutes = date.getMinutes()
var ampm = Number(hours) >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour ’0′ should be ’12′
var minutesStr = Number(minutes) < 10 ? '0'+ minutes : minutes;
estDeliveryTime = hours + ':' + minutesStr + ' ' + ampm;
so i need estDeliveryTime to be just hh:mm AM/PM format. my above code need to be fixed.
It is always a good idea to convert your date to UTC time set always as it is a common standard. Like for input date, just convert the date like this:
var now = new Date(),
utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
Now, when you take input from user for delivery time(for that extra hour), do the same thing to that date, and add that hour to the utcDate and in the end, convert the UTC date to GMT date with 5.5 as for IST.
Hope this helps:)
npm i --save date-fns
import {format} from "date-fns" in your .ts file
let example_time = "2019-11-30T14:42:30.951+08:00";
format(new Date(example_time), "HH:mm");
console.log(example_time) => '14:42'

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 .

Javascript display various time zones

The following script should be displaying the current local time based on the offset of -10 (Hawaii), but it's not working.
Can't figure out where I'm going wrong.
<h3>Current Time in Arizona is
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var 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("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
//-->
</script>
</h3>
First of all, the code you've shown just returns the current local time. It doesn't even attempt to change it for a specific time zone.
Secondly, you need to read the timezone tag wiki. In particular, read the section titled "Time Zone != Offset".
Now it just so happens that Arizona and Hawaii don't currently use daylight saving time, so you could adjust by offset if those were your only two concerns. But I'm sure you are looking for a more general solution.
To do it properly, you will need a library that implements the IANA time zone database. I list several of them here. For example, here is an example of displaying the current time in Los Angeles using moment.js with the moment-timezone plugin:
moment().tz("America/Los_Angeles").format("h:mm a")
If you're just looking for a quick and easy way to put a clock on your web site for a particular time zone, then I recommend using the free solution offered by timeanddate.com.
Write a function to move a Date by some offset in minutes/your choice
function offsetDate(offsetMinutes, d) {
if (d) d = new Date(d);
else d = new Date();
if (offsetMinutes) d.setUTCMinutes(d.getUTCMinutes() + offsetMinutes);
return d;
}
offsetDate(-10*60); // Thu Sep 05 2013 12:03:06 GMT+0100 (GMT Daylight Time)
Now use UTC functions to get the time

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