admin管理员组文章数量:1297053
I have been trying to write a script that will take the current time in Denver and output it into a URL.
I have been able to get this far: /
JS
$(function() {
var today = new Date();
var ss = today.getUTCSeconds();
var nn = today.getUTCMinutes() - 3; //3 minute delay
var hh = today.getUTCHours() - 6; //Offset UTC by 6 hours (Mountain Time)
var dd = today.getUTCDate();
var mm = today.getUTCMonth() + 1; //January is 0!
var yyyy = today.getUTCFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
if (hh < 10) {
hh = '0' + hh
}
var today = mm + '/' + dd + '/' + yyyy + '%20' + hh + ':' + nn + ':' + ss ;
$('img.r').each(function() {
var url = $(this).attr('src');
if (url.indexOf("?") >= 0) {
$(this).attr("src", url + today);
} else {
$(this).attr("src", url + "?feature_date=" + today);
}
});
});
HTML
<script src=".2.1/jquery.min.js"></script>
<script type="text/javascript" src="screen.js"></script>
<img class="r" src=";DateTime=" width="400">
It inserts the date into the URL however from 6pm-12am Mountain Time the time breaks (01:00:00 10/20/2018 bees -5:00:00 10/20/2018 instead of 19:00:00 10/19/2018) and the 3 minute delay offset makes it break every hour from :00-:02 (1:01 bees 1:-02 instead of 00:59).
I was wondering how I can fix the UTC offset so it doesn't subtract into negatives and offsets the date/month/year as appropriate.
I have been trying to write a script that will take the current time in Denver and output it into a URL.
I have been able to get this far: http://jsfiddle/Chibears85/h41wu8vz/4/
JS
$(function() {
var today = new Date();
var ss = today.getUTCSeconds();
var nn = today.getUTCMinutes() - 3; //3 minute delay
var hh = today.getUTCHours() - 6; //Offset UTC by 6 hours (Mountain Time)
var dd = today.getUTCDate();
var mm = today.getUTCMonth() + 1; //January is 0!
var yyyy = today.getUTCFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
if (hh < 10) {
hh = '0' + hh
}
var today = mm + '/' + dd + '/' + yyyy + '%20' + hh + ':' + nn + ':' + ss ;
$('img.r').each(function() {
var url = $(this).attr('src');
if (url.indexOf("?") >= 0) {
$(this).attr("src", url + today);
} else {
$(this).attr("src", url + "?feature_date=" + today);
}
});
});
HTML
<script src="https://ajax.googleapis./ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="screen.js"></script>
<img class="r" src="https://mywebsite.&DateTime=" width="400">
It inserts the date into the URL however from 6pm-12am Mountain Time the time breaks (01:00:00 10/20/2018 bees -5:00:00 10/20/2018 instead of 19:00:00 10/19/2018) and the 3 minute delay offset makes it break every hour from :00-:02 (1:01 bees 1:-02 instead of 00:59).
I was wondering how I can fix the UTC offset so it doesn't subtract into negatives and offsets the date/month/year as appropriate.
Share Improve this question edited Oct 19, 2018 at 19:49 benvc 15.1k4 gold badges38 silver badges57 bronze badges asked Oct 19, 2018 at 18:14 user1200940user1200940 391 gold badge1 silver badge7 bronze badges 10- Are you able to use a plugin ? if so, you can use MomentJS, have a look at the documentation first, if you think you can take help from some plugin, try to do the calculation with that, if you face any plexity, may be I can help to solve it with that, Doing so would decrease a lot of code plexity and momentjs would be able to take care of the calculations without any errors relating to timezone or whatever – Towkir Commented Oct 19, 2018 at 18:19
- I can use MomentJS, I was looking into it earlier today trying to solve the issue but I ran into not being able to figure out how to have MomentJS output the date into the URL for my image. – user1200940 Commented Oct 19, 2018 at 18:22
- so, what you need is to get the current time of Denver and set that to an image's src attribute right ? – Towkir Commented Oct 19, 2018 at 18:29
-
Browsers have varying levels of support for
toLocaleString
options, but depending on your requirements you may be able to usenew Date().toLocaleString('en-US', {timeZone: 'America/Denver'})
– benvc Commented Oct 19, 2018 at 18:31 - 1 The images upload to the server every 3 minutes, but are labled as the exact time they were created instead of published (Image created on 12:03 won't be pushed to server until 12:06) – user1200940 Commented Oct 19, 2018 at 19:52
3 Answers
Reset to default 6Depending on your browser support needs, you may be able to use toLocaleString
but be aware that locales and options may not be supported in Edge and are not supported in Android webview.
new Date().toLocaleString('en-US', {timeZone: 'America/Denver'})
To follow your function through to conclusion and convert UTC time to Mountain Time manually (either Mountain Standard Time or Mountain Daylight Time depending on the time of year), you would have to extend your function to handle daylight savings. For example (this is why libraries like Moment.js are so popular, and may be worth looking into for your needs):
const twoDigit = (d) => (d < 10 ? '0' : '') + d;
const formatDate = (date, time) => {
date = date.map((x) => twoDigit(x)).join('/');
time = time.map((x) => twoDigit(x)).join(':');
return `${date} ${time}`;
};
const getOffset = (month, date, day, hour) => {
// assume MST offset
let offset = 7;
// adjust to MDT offset as needed
if ((month > 2 && month < 10) || (month === 2 && date > 14)) {
offset = 6;
} else if (month === 2 && date > 7 && date < 15) {
if ((day && date - day > 7) || (day === 0 && hour - offset >= 2)) {
offset = 6;
}
} else if (month === 10 && date < 8) {
if ((day && date - day < 0) || (day === 0 && hour - offset < 1)) {
offset = 6;
}
}
return offset;
};
const getMountainTime = () => {
const dt = new Date(); // current datetime
let year = dt.getUTCFullYear(); // utc year
let month = dt.getUTCMonth(); // utc month (jan is 0)
let date = dt.getUTCDate(); // utc date
let hour = dt.getUTCHours(); // utc hours (midnight is 0)
let minute = dt.getUTCMinutes(); // utc minutes
let second = dt.getUTCSeconds(); // utc seconds
let day = dt.getUTCDay(); // utc weekday (sunday is 0)
let offset = getOffset(month, date, day, hour);
if (hour - offset < 0) {
hour = 24 + hour - offset;
day = day ? day - 1 : 6;
if (date === 1) {
if (!month) {
year -= 1;
month = 11;
} else {
month -= 1;
}
date = new Date(year, month + 1, 0).getDate();
} else {
date -= 1;
}
} else {
hour -= offset;
}
month += 1;
return formatDate([month, date, year], [hour, minute, second]);
};
const denver = getMountainTime();
console.log(denver);
This can be solved with pure JS, though I thought of using MomentJS at first. A good solution would be this:
var today = new Date();
var todayThreeMinutesLess = new Date(today - (3 * 60000)); // to reduce 3 minutes from current time, as 60000 ms is 1 minute;
var today = todayThreeMinutesLess.toLocaleString('en-US', {timeZone: 'America/Denver', hour12: false}).replace(', ', '%20');
$('img.r').each(function() {
var url = $(this).attr('src');
if (url.indexOf("?") >= 0) {
$(this).attr("src", url + today);
} else {
$(this).attr("src", url + "?feature_date=" + today);
// just to prevew the url format
$(this).attr("alt", url + "?feature_date=" + today);
}
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img class="r" src="https://mywebsite.&DateTime=" width="400">
You can also use date-fnc library for this.
import { formatToTimeZone } from 'date-fns-timezone';
const value = new Date();
const pattern = 'MMM. DD, YYYY [at] H:mma [MT]';
const outputDate = formatToTimeZone(value, pattern, { timeZone: 'MST' })
This is a link to format options https://date-fns/v1.9.0/docs/format
And this is for date-fnc time zones https://date-fns/v2.0.0-alpha.27/docs/Time-Zones
本文标签: datetimeJavaScript How to convert UTC datetime to Mountain TimeStack Overflow
版权声明:本文标题:datetime - JavaScript: How to convert UTC datetime to Mountain Time? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741619704a2388737.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论