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'
Related
This question already has answers here:
How to add 30 minutes to a JavaScript Date object?
(29 answers)
Closed 2 years ago.
I have to get +15 minutes date time in Javascript with dd/mm/yyyy hh:ii AM/PM format.
And I should compare two dates, which are in dd/mm/yyyy hh:ii AM/PM format.
JS:
var date = new 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'
hours = hours < 10 ? '0' + hours : hours;
minutes = minutes < 10 ? '0' + minutes : minutes;
var dd = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
var mm = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1);
var strTime = dd + '/' + mm + '/' + date.getFullYear() + " " + hours + ':' + minutes + ' ' + ampm;
let me first note that by default javascript would be giving you the time in UTC.
A JavaScript date is fundamentally specified as the number of milliseconds that have elapsed since midnight on January 1, 1970, UTC. This date and time are the same as the UNIX epoch, which is the predominant base value for computer-recorded date and time values. (refer)
The above is true when you use the Date() function to create a Date Object
Using ES20xx, you can use a template literal (not supported in IE) and the padStart(not supported in IE) string extension to format the Date object to your liking as shown in the snippet below.
I have also date.toLocaleString() which gives the string in a format that is commonly used in the region from where the browser is running the function
The toLocaleString() method returns a string with a language sensitive
representation of this date. The new locales and options arguments let
applications specify the language whose formatting conventions should
be used and customize the behavior of the function. In older
implementations, which ignore the locales and options arguments, the
locale used and the form of the string returned are entirely
implementation dependent.(refer)
So the easy way to do this would be to add 15 minutes to the Unix timestamp obtained from the Date Object and formatting it with toLocaleString(this is the first snippet)
You can also compare the two date objects below as you would any integer
var dt1 = (new Date()).getTime();//Unix timestamp (in milliseconds)
console.log("Current date Unix timestamp(ms)")
console.log(dt1)
console.log("15 mins later date Unix timestamp(ms)")
console.log(dt1+900000)//15min=900000ms (15*60*1000)
var dt = new Date(dt1);
var dt2= new Date(dt1+900000)
console.log("Unformatted dates 15 min apart (ISO 8601 / UTC)")
console.log(dt)
console.log(dt2)
console.log("Formatted dates 15 min apart (According to your timezone)")
console.log(dt.toLocaleString())
console.log(dt2.toLocaleString())
Below is the longer snippet that involves formatting the date object while displaying it. I feel this is not as optimal as the method above. But still does the job.
var dt = new Date();
console.log(dt);
const localdte = dt.toLocaleString();
console.log(localdte);
const [dated, time, ampm] = localdte.split(' ');
const [hh, mm, ss] = time.split(':');
var date = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
dt.getHours().toString().padStart(2, '0')}:${
dt.getMinutes().toString().padStart(2, '0')}`
console.log("Date right now");
console.log(date);
console.log("date 15 mins later");
var date15 = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
(dt.getMinutes()>44?(dt.hours==23?00:dt.getHours()+1):dt.getHours()).toString().padStart(2, '0')}:${
((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
console.log("24 hour format " + date15);
if (ampm == "PM" && hh != 12 && hh!=00) {
var date15 = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
(dt.getMinutes()>44?(dt.getHours()+1)%12:dt.getHours()%12).toString().padStart(2, '0')}:${
((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
console.log("12 hour format " + date15 + ampm); //12 hour format
} else if (hh == 00) {
var date15 = `${
dt.getDate().toString().padStart(2, '0')}/${
(dt.getMonth()+1).toString().padStart(2, '0')}/${
dt.getFullYear().toString().padStart(4, '0')} ${
(dt.getMinutes()>44?1:12).toString().padStart(2, '0')}:${
((dt.getMinutes()+15)%60).toString().padStart(2, '0')}`
console.log("12 hour format " + date15 + ampm);
} else {
console.log("12 hour format " + date15 + ampm); //12 hour format
}
const dateISO = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate(), dt.getHours(), ((dt.getMinutes() + 15) % 60), dt.getMilliseconds());
console.log("ISO 8601 format (UTC)");
console.log(dateISO);
Note: there is a difference in the chrome console and the snippet console outputs. In the chrome console the output the date object is always formatted for local time. In the snippet console, the output of the date object is in UTC and ISO8601 compliant.
Thanks to #RobG for pointing out the errors in my previous answer.
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 }))
I want to add 30 days to a Date (including the timestamp), however, the timestamp is being calculated from the execution time of the script instead of the source data (loadStartDateTime).
I created a new date object and then set the date (purge_date = loadStartDateTime + 30days).
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
PURGEDATE = (function (loadTime) {
var loadDate = new Date(loadTime);
var purge_date = new Date();
purge_date.setDate(loadDate.getDate()+30);
var month = purge_date.getMonth() + 1;
var mm = month < 10 ? "0" + month : month;
var day = purge_date.getDate();
var dd = day < 10 ? "0" + day : day;
var hours = purge_date.getHours() < 10 ? "0" + purge_date.getHours() : purge_date.getHours();
var minutes = purge_date.getMinutes() < 10 ? "0" + purge_date.getMinutes() : purge_date.getMinutes();
var seconds = purge_date.getSeconds() < 10 ? "0" + purge_date.getSeconds() : purge_date.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
var yyyy = purge_date.getFullYear();
return mm + "/" + dd + "/" + yyyy + time;
})(LoadStartDateTime)
The Result:
loadStartDateTime | PurgeDate
8/7/2018 5:55:45 PM | 09/06/2018 10:28:49
8/7/2018 5:58:10 PM | 09/06/2018 10:28:49
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
Thank you~
After further investigation I realized that:
The Date object’s constructor is ISO 8601
When I use getDate() I do not provide the timezone explicitly.
This causes the timestamp to be 00:00:00 local time, so I should use getTime() method instead to get the timestamp. Since in JavaScript a timestamp is the number of milliseconds, a simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:
30 * 24 * 60 * 60 * 1000
Finally, sum both values and send the result as a param in the constructor:
For example:
loadStartDateTime = new Date('8/7/2018 5:55:45 PM');
test_date = loadStartDateTime.getTime() + (30 * 24 * 60 * 60 * 1000);
test_date = new Date(test_date);
and then can continue with the Date Formatting.
I found the solution combining the answers from ISO 8601 date format - Add day with javascript and Add 30 days to date (mm/dd/yy). This guide "The Definitive Guide to DateTime Manipulation" helped to find out when I was wrong by understanding more about DateTime Manipulation.
I am getting a string formatted date with UTC timezone. I need to convert this date time in user's current time zone using jquery or javascript.
I am getting this:
9:43pm 16/10/2015 //this is UTC time, I am getting this via an ajax call
I need to convert it to this:
12:00pm 16/10/2015 //whatever time by that location
If you can pick that format apart, or get a standard format JavaScript can parse - you can convert it to a Date object. I'm not seeing an offset on that date which is problematic when JavaScript tries to parse it. Assuming that is all you have, we can force a UTC date with the following...
// ------- new Date(Date.UTC(year, month, day, hour, minute, second))
var date = new Date(Date.UTC(2015, 9, 16, 21, 43, 0));
console.log(date) // Fri Oct 16 2015 15:43:00 GMT-0600 (Mountain Daylight Time (Mexico))
note that month in Date.UTC is zero based e.g. October would be 9
new Date(value) would do this for us automatically if the format is correct - where value is the actual date value you receive - but that format will not parse as is. If there is no way around that format, you can manipulate it to work in the above example. Here is an untested algorithm for your example...
var formatted = '9:43pm 16/10/2015'
function createDateUTC(formatted) {
var hourOffset = formatted.split(' ')[0].split(':')[1].match(/[a-zA-Z]+/g)[0] === 'pm' ? 12 : 0
var year = parseInt(formatted.split('/').pop());
var month = parseInt(formatted.split('/')[1]) - 1;
var day = parseInt(formatted.split('/')[0].split(' ').pop());
var hour = hourOffset + parseInt(formatted.split(' ')[0].split(':')[0]);
var minute = parseInt(formatted.split(' ')[0].split(':')[1]);
return new Date(Date.UTC(year, month, day, hour, minute, 0));
}
var myDate = createDateUTC(formatted);
JSFiddle Link - working demo
Check out the UTC() and Date Object docs for more info
Additionally, to get the exact format you want, we can introduce some more functions which will give us the 12:00pm 16/10/2015 format
function formatAMPM(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 strTime;
}
function formatMMDDYYYY(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
console.log(formatAMPM(myDate) + ' ' + formatMMDDYYYY(myDate));
// Mountain Daylight Time => -- 3:43pm 16/10/2015
JSFiddle Link - formatted example
I'd reccoment looking into Moment.js if you plan to do heavy date formatting and manipulation.
Overall - the best solution to this would be to return an acceptable format from the server, resolve it to local time natively e.g. new Date(), and use a robust formatting library as opposed to rolling your own to display it how you wish.
You should process that string a little bit to extract year, month, day, hour and minute.
Then you can create a local date with that UTC date using this:
var time = new Date ( Date.UTC('year', 'month', 'day', 'hour', 'minute') );
In my case, '9:43pm 16/10/2015' returns: 'Mon Nov 16 2015 07:43:00 GMT-0200 (Hora de verano de Argentina)'.
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