Date/Time format in Javascript - 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 .

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!

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

Javascript Concatenate dates and time together

I have this code which generates the current date + time in javascript:
var date_variable = new Date();
var year = date_variable.getFullYear();
var month = date_variable.getMonth() + 1;
var day = date_variable.getDate();
var hour = date_variable.getHours();
var minutes = date_variable.getMinutes();
var seconds = date_variable.getSeconds();
var full_date = year + month + day + hour + minutes + seconds;
console.log(year);
console.log(month);
console.log(day);
console.log(hour);
console.log(minutes);
console.log(seconds);
console.log(full_date);
Everything in console displays fine, except when it comes to the full_date variable. This is what's displayed in console:
2014
8
27
10
53
10
2122
My question is, why does the last output not combine my date + time into a single string?
Thanks
You need to concatenate the numbers with a string first.
var full_date = year +""+ month +""+ day +""+ hour +""+ minutes +""+ seconds;
Each of the properties you are accessing return a number. When you add them together with the + operator, you are just adding numbers together.
If you substitute the variables used in full date, it would look something like:
var full_date = 2014 + 8 + 26 + . . .
All you have to do is put a strings in the expression and you will get what you want.
In all honesty though, you should use Date.toLocalDateString() or Date.toLocalTimeString() if the format works for you. You can read the documentation about them on MDN's Date reference page.

Converting isotime to shorttime in javascript

I have a ajax call which returns a time e.g 16:06:59 i want to convert it to 4:06 PM
var mydate = obj[0].time;
mydate comes 16:06:59 but when i try to use it with var date = new Date(), it gives me todays date .
Is there any solution to realize what i want ?
Thanks
The simplest answer is to split it into parts and then use them however you want, e.g.:
var parts = obj[0].time.split(":");
// parts[0] is now "16"
// parts[1] is now "06"
// parts[2] is now "59"
// Then perhaps (to get numbers and give the parts names)
var hours = parseInt(parts[0], 10);
var minutes = parseInt(parts[1], 10);
var seconds = parseInt(parts[2], 10);
...and of course for the first one you can use:
if (hours > 12) {
hours -= 12;
}
...if you want to do the a.m./p.m. thing. Just remember you did that and set your a.m./p.m. variable accordingly.
If you really want a Date instance, you can do this:
var dt = new Date();
dt.setHours(hours); // Be sure to use the real value here, not the one -12
dt.setMinutes(minutes);
dt.setSeconds(seconds);
try this :
function Convert24HoursTo12(time) {
var timeArray = time.split(':');
var hours = timeArray[0];
var minutes = timeArray[1];
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
and call it:
Convert24HoursTo12(obj[0].time);
See Demo Here.
You can do this:
"16:06:59".split(':').slice(0, 2)
.map(function (x, index) {
return index == 0 ? (x > 12 ? x - 12 + "PM" : x + "AM") : x
}).join(":").replace(/(.+?)((P|A)M)(.+)/, "$1$4 $2");
Modify the following code according to your need
var mydate= new Date();
var myhour=mydate.getHours();
var ampm="AM";
if(myhour==12)ampm="PM";
if(myhour==0)myhour=12;
if (myhour>12){
myhour-=12;
ampm="PM";
}else{
myhour=mydate.getHours();
}
var mytime=myhour+":"+mydate.getMinutes()+":"+mydate.getSeconds()+" "+ampm;
then use mytime variable anywhere you want
I have not checked it as I am in a hurry now. I hope it works well.

Adjusting JavaScript Date and Time [duplicate]

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

Categories

Resources