Only enable during 2 weeks date format html - javascript

I have a problem enabling only during 2 weeks data format. For example, I want only to show today and before 14 days. Now my coding just can lock before days.
Scenario:
If today 03 Feb 2021, I want to enable dates are 20 Jan 2021 until 03 Feb 2021. Other dates will be disabled.
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("accident")[0].setAttribute('min', today);
<input type="date" class="form-control" id="accident" name="accident" value="" title="Date of Accident">
Now my result like below the picture:
Hope someone can guide me on which part I am getting wrong it. Thanks.

According to MDN Documentation. You need to set min and max values to specify an interval
// Get date objects
const today = new Date();
const twoWeeksAgo = new Date();
twoWeeksAgo.setDate(today.getDate() - 14);
// Then set in input
const input = document.querySelector('[name=accident]');
input.setAttribute('min', twoWeeksAgo.toISOString().slice(0, 10));
input.setAttribute('max', today.toISOString().slice(0, 10));
<input type="date" name="accident" />

You only set min, but you did not set max.
Because of this relationship, it only knows your minimum date, but does not know your maximum date, so the previous result is normal, as long as you make up the setting, it will work.
For details, please refer to here.
const getDateStr = (d) => d.toISOString().split('T')[0];
const daysRange = (days) => {
const d = new Date();
const when = new Date(d.setDate(d.getDate() + days));
return [new Date(), when].map(m=>getDateStr(m));
};
const limit = daysRange(-14);
const picker = document.getElementsByName("accident")[0];
picker.setAttribute('min', limit[1]);
picker.setAttribute('max', limit[0]);
picker.setAttribute('value', limit[0]);
label {
display: block;
font: 1rem 'Fira Sans', sans-serif;
}
input,
label {
margin: .4rem 0;
}
<label for="start">date:</label>
<input type="date" name="accident">

The solution you're looking for is something like this,
const twoWeeksAgo = 14 * 24 * 60 * 60 * 1000;
let dateElement = document.querySelector('#accident');
dateElement.min = new Date(Date.now() - twoWeeksAgo).toISOString().split('T')[0];
dateElement.max = new Date().toISOString().split('T')[0];
<input type="date" class="form-control" id="accident" name="accident" value="" title="Date of Accident">
You can use the max and min attributes of the HTML5 date element (documented here) to restrict your element to only show certain values.
In this particular case, the min attribute is set to the date (in yyyy-mm-dd format) two weeks ago and the max attribute is set to the current date.
The magic computation twoWeeksAgo is the number of milliseconds in 14 days which will allow you to compute the date 14 days ago.
The code new Date(Date.now() - twoWeeksAgo) gives us a Date object set to two weeks ago and the .toISOString() function returns the date in YYYY-MM-DDTHH:mm:ss.sssZ format, i.e., a date-time string.
Since the min attribute only requires the date and not the time, we then split the obtained string using 'T' as a delimiter, which would give us the date in YYYY-MM-DD format.
Putting it all together we get this line for the date two weeks ago
dateElement.min = new Date(Date.now() - twoWeeksAgo).toISOString().split('T')[0];
And similarly for the upper limit date,
dateElement.max = new Date().toISOString().split('T')[0];

Related

html date form: how to set start date as tomorrow using Javascript

Trying to limit the start date as tomorrow (local date). Can someone tell why below code isn't working:
<form method="POST">
<div>
<label for="s2">pickup_date</label>
<input type = 'date' name='pickup_date' required>
<br /><br />
</div>
</form>
<script>
var time = new Date();
var localTimeStr = time.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
today = new Date(localTimeStr)
tomorrow = new Date(today.setDate(today.getDate() + 1)).toISOString().split('T')[0];
t = String(tomorrow)
document.getElementsByName("pickup_date")[0].setAttribute('min', t);
</script>
the output of below code is 2022-01-18:
var time = new Date();
var localTimeStr = time.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
today = new Date(localTimeStr)
tomorrow = new Date(today.setDate(today.getDate() + 1)).toISOString().split('T')[0];
t = tomorrow.split('-')[0]+'-'+tomorrow.split('-')[1]+'-'+tomorrow.split('-')[2]
console.log(t)
however, the calendar start date in the form is still 2022-01-17. But, when I manually set
document.getElementsByName("pickup_date")[0].setAttribute('min', '2022-01-18');
the calendar start from 2022-01-18 correctly. why!
In the OP there is:
var time = new Date();
var localTimeStr = time.toLocaleString('en-US', { timeZone: 'Asia/Shanghai' });
today = new Date(localTimeStr)
That will return a timestamp with the date and time for Shanghai.
tomorrow = new Date(today.setDate(today.getDate() + 1)).toISOString().split('T')[0];
That will firstly parse the string assigned to today as "local" to the host system using the built–in parser, which it is not required to do by ECMA-262 (see Why does Date.parse give incorrect results?).
It will then return an ISO 8601 formatted string for the equivalent UTC date and time. If the host system's offset is positive, then depending on the time in the timestamp, the date will either be the same day or the previous day. Similarly, for hosts with a negative offset, the date might be the same day or the following day depending on the time in the string and the host system's offset.
There are many questions on formatting dates, the various toLocaleString methods are useful but I don't know how reliable they are in the long term. To get an ISO 8601 formatted local date, the format associated with the language en-CA seems to suit:
new Date().toLocaleDateString('en-CA')
If you want to get timestamps for the current date and tomorrow in Shanghai in YYYY-MM-DD format, consider:
let d = new Date();
let today = d.toLocaleDateString('en-CA', {timeZone:'Asia/Shanghai'});
d.setDate(d.getDate() + 1);
let tomorrow = d.toLocaleDateString('en-CA', {timeZone:'Asia/Shanghai'});
console.log(`Today : ${today}\nTomorrow: ${tomorrow}`);

JavaScript: unexpected result getting number of days remaining in the month

I'm building a simple script to show the number of days to the end of the month to demonstrate an understanding of how dates work in Javascript. Which is just as well, because I clearly don't have one.
I want to get the current date, and compare it to the last day of the month, as date(this year, this month +1, day 0) - 1 day to see how many days are left. I could build an array telling it how many days are in each month, but I should be able to use the inbuilt understanding of dates to resolve this.
For expected output, last day of this month (Aug 31) - today (Aug 30) = 1. But I'm getting 0.
This is what I have so far:
<p id="demo"></p>
<script>
var d = new Date();
var nxt = new Date(d.getFullYear(), d.getMonth() + 1, 0);
nxt.setDate(nxt.getDate() - 1);
document.getElementById("demo").innerHTML = nxt.getDay() - d.getDay();
</script>
At the moment it's 11 in AEST (GMT + 1000), which is where I'm at in case that's of any help. Point is to make something that would work anywhere, any time.
My first suspect is timezones - I thought that this might even out if I used all UTC or no UTC explicits. It doesn't seem to be doing so though. I've tried asking for UTC values in a range of different places, but oddly only seem to be able to increase the inaccuracy so it returns -1.
I believe I just stumbled on the answer - when specifying a date months are counted from 0 to 11, but days are still counted from 1 to 31. Therefore, specifying
Date(d.getFullYear(), d.getMonth() + 1, 0);
is basically shorthand for the last day of the current month. The next line is then redundant:
nxt.setDate(nxt.getDate() - 1);
This will give an incorrect result, as it basically decrements a second time. The problem is not with UTC/nonUTC, but rather incorrect day specification. Not sure if this shorthand could cause other problems further down the line though.
For anyone wondering why the day zero value results in that behavior, JavaScript... return last available date of calendar provides a useful explanation.
The following vanilla js approach to calculating days remaining in the month is just a slight variation on what you are doing with brief comment explanation of how to take advantage of month index and day zero to get the last day of the current month.
const year = 2018;
const month = 7; // months indexed from 0 (Jan) to 11 (Dec)
const day = 30;
// current datetime
const date = new Date(year, month, day);
// add 1 to get next month, set day to 0 to roll it back to last day of current month
const last = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
// difference between last day of the month and input date
const diff = last - date.getDate();
console.log(diff);
Below is a snippet where you can experiment with the results for different dates.
const remainDays = (y, m, d) => {
const result = document.querySelector('#result');
const date = new Date(y, m, d);
const last = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
const diff = last - date.getDate();
result.textContent = diff;
};
const year = document.querySelector('#year');
const month = document.querySelector('#month');
const day = document.querySelector('#day');
const button = document.querySelector('button');
remainDays(year.value, month.value, day.value);
button.addEventListener('click', () => {
remainDays(year.value, month.value, day.value);
});
div {
padding: 5px;
display: flex;
flex-direction: column;
max-width: 400px;
}
<div>
<label for="year">Year</label>
<input id="year" name="year" type="text" value="2018" />
</div>
<div>
<label for="month">Month Index</label>
<input id="month" name="month" type="text" value="7" />
<span>Enter month index between 0 (Jan) and 11 (Dec)</span>
</div>
<div>
<label for="day">Day</label>
<input id="day" name="day" type="text" value="30" />
</div>
<div>
<button>Get Month Days Remaining</button>
</div>
<div>
<span>Result:</span>
<span id="result"></span>
</div>
You have to remember that in browser the dates are always in the current system setting timezone.
If you can use the moments library, that can solve all the date related common problems by providing you almost all the functions you may need
Here is the datediff sample code:
var today = new Date(), y = today.getFullYear(), m = today.getMonth();
var lastDay = new Date(y, m + 1, 0);
var diff = lastDay.diff(today, 'days', true);
now since both the dates are created in the same browser they will have same timezone an will not create any issue. But if one date is say returned from server and is represented in say GMT/UTC then you need to convert the other date too in the same timezone. Again, the moments.js will be able to help there.

Need to compare new date with datepicker

Im struggling with dates in javascript. Im going to compare some dates input but the user and the date the user input depends which list the information goes. My issue is comparing the system date and the date picker date. The system date shows the format of 'Tue Dec 22 2015 00:00:00 GMT+0000 (GMT)' date picker shows 22/12/2015. How can i change the system date to match the date picker format so i can compare dates? I want to do it without jQuery(i know date picker goes against this).
Here my code so far for the date which basically is just setting the time to 00:00:00.
var today = new Date();
today.setHours(0,0,0,0);
var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
yesterday.setHours(0,0,0,0);
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
tomorrow.setHours(0,0,0,0);
console.log(today);
var dateTask = document.getElementById("date").value;
console.log(dateTask);
You have to parse the user input into a Date object. 22/12/2015 is not a valid datestring for the Date constructor so you have to parse it yourself.
You can do something like this:
var dateSplit= document.getElementById("date").value.split('/'),
dateTask = new Date(dateSplit[2],dateSplit[1]-1,dateSplit[0], 0, 0, 0, 0);
Note: this code is very basic and needs an enhancement when you're parsing real user input.
After that you can compare the dates like this:
today.getTime() === dateTask.getTime()
Just split the string with str.split("/"); and construct Date in one of the ways that is pointed out here.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Date
be careful months are from 0-11
You don't actually need JQuery if you want a date-picker, but that's beside the point. I think the best approach is to parse the user input as a date using Date.parse. You can then compare them as unix epoch timestamps.
"use strict";
var datePicker = document.querySelector('#date');
datePicker.addEventListener('change',function(){
var udate = Date.parse(this.value);
var sysdate = Date.now();
document.querySelector('#d').innerText = udate;
document.querySelector('#sys').innerText = sysdate;
});
form {
position: relative;
}
label, input, output {
float: left;
}
label {
clear: left;
width: 128px;
}
<form>
<label for="date">user input</label>
<input type="date" name="date" id="date">
<label for="d">user date</label>
<output id="d" name="d" for="date"></output>
<label for="sys">system date</label>
<output id="sys" name="sys"></output>
</form>
const datePicker = document.querySelector("#date");
const todayDate = new Date().toLocaleDateString();
const datePickerValue = new Date(datePicker.value).toLocaleDateString();
datePicker.addEventListener("change", () => {
if (datePickerValue === todayDate) {
alert("");
} else {
alert("");
}
});

Simple javascript date math... not really

I am trying to create a simple script that gives me the next recycling date based on a biweekly schedule starting on Wed Jul 6, 2011. So I've created this simple function...
function getNextDate(startDate) {
if (today <= startDate) {
return startDate;
}
// calculate the day since the start date.
var totalDays = Math.ceil((today.getTime()-startDate.getTime())/(one_day));
// check to see if this day falls on a recycle day
var bumpDays = totalDays%14; // mod 14 -- pickup up every 14 days...
// pickup is today
if (bumpDays == 0) {
return today;
}
// return the closest day which is in 14 days, less the # of days since the last
// pick up..
var ms = today.getTime() + ((14- bumpDays) * one_day);
return new Date(ms);
}
and can call it like...
var today=new Date();
var one_day=1000*60*60*24; // one day in milliseconds
var nextDate = getNextDate(new Date(2011,06,06));
so far so good... but when I project "today" to 10/27/2011, I get Tuesday 11/8/2011 as the next date instead of Wednesday 11/9/2011... In fact every day from now thru 10/26/2011 projects the correct pick-up... and every date from 10/27/2011 thru 2/28/2012 projects the Tuesday and not the Wednesday. And then every date from 2/29/2012 (leap year) thru 10/24/2012 (hmmm October again) projects the Wednesday correctly. What am I missing? Any help would be greatly appreciated..
V
The easiest way to do this is update the Date object using setDate. As the comments for this answer indicate this isn't officially part of the spec, but it is supported on all major browsers.
You should NEVER update a different Date object than the one you did the original getDate call on.
Sample implementation:
var incrementDate = function (date, amount) {
var tmpDate = new Date(date);
tmpDate.setDate(tmpDate.getDate() + amount)
return tmpDate;
};
If you're trying to increment a date, please use this function. It will accept both positive and negative values. It also guarantees that the used date objects isn't changed. This should prevent any error which can occur if you don't expect the update to change the value of the object.
Incorrect usage:
var startDate = new Date('2013-11-01T11:00:00');
var a = new Date();
a.setDate(startDate.getDate() + 14)
This will update the "date" value for startDate with 14 days based on the value of a. Because the value of a is not the same is the previously defined startDate it's possible to get a wrong value.
Expanding on Exellian's answer, if you want to calculate any period in the future (in my case, for the next pay date), you can do a simple loop:
var today = new Date();
var basePayDate = new Date(2012, 9, 23, 0, 0, 0, 0);
while (basePayDate < today) {
basePayDate.setDate(basePayDate.getDate()+14);
}
var nextPayDate = new Date(basePayDate.getTime());
basePayDate.setDate(nextPayDate.getDate()-14);
document.writeln("<p>Previous pay Date: " + basePayDate.toString());
document.writeln("<p>Current Date: " + today.toString());
document.writeln("<p>Next pay Date: " + nextPayDate.toString());
This won't hit odd problems, assuming the core date services work as expected. I have to admit, I didn't test it out to many years into the future...
Note: I had a similar issue; I wanted to create an array of dates on a weekly basis, ie., start date 10/23/2011 and go for 12 weeks. My code was more or less this:
var myDate = new Date(Date.parse(document.eventForm.startDate.value));
var toDate = new Date(myDate);
var week = 60 * 60 * 24 * 7 * 1000;
var milliseconds = toDate.getTime();
dateArray[0] = myDate.format('m/d/Y');
for (var count = 1; count < numberOccurrences; count++) {
milliseconds += week;
toDate.setTime(milliseconds);
dateArray[count] = toDate.format('m/d/Y');
}
Because I didn't specify the time and I live in the US, my default time was midnight, so when I crossed the daylight savings time border, I moved into the previous day. Yuck. I resolved it by setting my time of day to noon before I did my week calculation.

Convert UTC Epoch to local date

I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass new Date() an epoch, it assumes it’s local epoch. I tried creating a UTC object, then using setTime() to adjust it to the proper epoch, but the only method that seems useful is toUTCString() and strings don’t help me. If I pass that string into a new date, it should notice that it’s UTC, but it doesn’t.
new Date( new Date().toUTCString() ).toLocaleString()
My next attempt was to try to get the difference between local current epoch and UTC current epoch, but I wasn’t able to get that either.
new Date( new Date().toUTCString() ).getTime() - new Date().getTime()
It’s only giving me very small differences, under 1000, which is in milliseconds.
Any suggestions?
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
d is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
It's easy, new Date() just takes milliseconds, e.g.
new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
And just for the logs, I did this using Moment.js library, which I was using for formatting anyway.
moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
Epoch time is in seconds from Jan. 1, 1970. date.getTime() returns milliseconds from Jan. 1, 1970, so.. if you have an epoch timestamp, convert it to a javascript timestamp by multiplying by 1000.
function epochToJsDate(ts){
// ts = epoch timestamp
// returns date obj
return new Date(ts*1000);
}
function jsDateToEpoch(d){
// d = javascript date obj
// returns epoch timestamp
return (d.getTime()-d.getMilliseconds())/1000;
}
function ToLocalDate (inDate) {
var date = new Date();
date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
return date;
}
Epoch time (i.e. Unix Epoch time) is nearly always the number of seconds that have expired since 1st Jan 1970 00:00:00 (UTC time), not the number of milliseconds which some of the answers here have implied.
https://en.wikipedia.org/wiki/Unix_time
Therefore, if you have been given a Unix Epoch time value it will probably be in seconds, and will look something like 1547035195. If you want to make this human readable in JavaScript, you need to convert the value to milliseconds, and pass that value into the Date(value) constructor, e.g.:
const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();
You don't need to do the d.setUTCMilliseconds(0) step in the accepted answer because the JavaScript Date(value) constructor takes a UTC value in milliseconds (not a local time).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
Also note that you should avoid using the Date(...) constructor that takes a string datetime representation, this is not recommended (see the link above).
var myDate = new Date( your epoch date *1000);
source - https://www.epochconverter.com/programming/#javascript
To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.
$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"
2/7/2018, 19:35:24
or as JS:
var date = new Date(Date.now());
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24
console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24
Note: The use of en-GB here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!
Addition to the above answer by #djechlin
d = '1394104654000';
new Date(parseInt(d));
converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.
The Easiest Way
If you have the unix epoch in milliseconds, in my case - 1601209912824
convert it into a Date Object as so
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toString()
output -
Sun Sep 27 2020 18:01:52 GMT+0530 (India Standard Time)
if you want the date in UTC -
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toUTCString()
Now you can format it as you please.
Considering, you have epoch_time available,
// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB'); // 24 hour format
The simplest solution I've found to this, is:
var timestamp = Date.now(), // returns milliseconds since epoch time
normalisedTime = new Date(timestamp);
Notice this doesn't have the * 1000 at the end of new Date(timestamp) statement as this (for me anyway!) always seems to give out the wrong date, ie instead of giving the year 2019 it gives the year as 51015, so just bear that in mind.
EDIT
var utcDate = new Date(incomingUTCepoch);
var date = new Date();
date.setUTCDate(utcDate.getDate());
date.setUTCHours(utcDate.getHours());
date.setUTCMonth(utcDate.getMonth());
date.setUTCMinutes(utcDate.getMinutes());
date.setUTCSeconds(utcDate.getSeconds());
date.setUTCMilliseconds(utcDate.getMilliseconds());
EDIT fixed
Are you just asking to convert a UTC string to a "local" string? You could do:
var utc_string = '2011-09-05 20:05:15';
var local_string = (function(dtstr) {
var t0 = new Date(dtstr);
var t1 = Date.parse(t0.toUTCString().replace('GMT', ''));
var t2 = (2 * t0) - t1;
return new Date(t2).toString();
})(utc_string);
If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.
For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.
The Number and Date extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.
I recommend you to check the Code Snippet down below to test this solution.
Conversions from milliseconds
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
Conversions from dates
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
Usage
// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();
// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();
See it for yourself
// Extending Number
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
// Extending Date
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
// Getting the demo to work
document.getElementById('m-to-local-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-local-display'),
value = document.getElementById('m-to-local').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toLocalDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('m-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-utc-display'),
value = document.getElementById('m-to-utc').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toUTCDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('date-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('date-to-utc-display'),
yearValue = document.getElementById('date-to-utc-year').value || '1970',
monthValue = document.getElementById('date-to-utc-month').value || '0',
dayValue = document.getElementById('date-to-utc-day').value || '1',
hourValue = document.getElementById('date-to-utc-hour').value || '0',
minuteValue = document.getElementById('date-to-utc-minute').value || '0',
secondValue = document.getElementById('date-to-utc-second').value || '0',
year = parseInt(yearValue),
month = parseInt(monthValue),
day = parseInt(dayValue),
hour = parseInt(hourValue),
minute = parseInt(minuteValue),
second = parseInt(secondValue);
displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime();
}, false);
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/>
<div class="ui container">
<p></p>
<h3>Milliseconds to local date</h3>
<input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button>
<em id="m-to-local-display">Set a value</em>
<h3>Milliseconds to UTC date</h3>
<input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button>
<em id="m-to-utc-display">Set a value</em>
<h3>Date to milliseconds in UTC</h3>
<input id="date-to-utc-year" placeholder="Year" style="width: 4em;" />
<input id="date-to-utc-month" placeholder="Month" style="width: 4em;" />
<input id="date-to-utc-day" placeholder="Day" style="width: 4em;" />
<input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" />
<input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" />
<input id="date-to-utc-second" placeholder="Second" style="width: 4em;" />
<button id="date-to-utc-button">Convert</button>
<em id="date-to-utc-display">Set the values</em>
</div>
#Amjad, good idea, but a better implementation would be:
Date.prototype.setUTCTime = function(UTCTimestamp) {
var UTCDate = new Date(UTCTimestamp);
this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
return this.getTime();
}

Categories