Skip to content

Commit

Permalink
Converts current date to the component's timezone
Browse files Browse the repository at this point in the history
  • Loading branch information
vyzaldysanchez committed Sep 18, 2020
1 parent db8af09 commit 6ae354f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/components/TimedContent.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
</template>

<script>
import { isValidTimeZone, isValidDate } from "../utils/helpers";
import { getTimeZonedDate, isValidTimeZone, isValidDate } from "../utils/helpers";
export default {
name: "TimedContent",
Expand All @@ -29,7 +29,7 @@ export default {
data() {
return {
countdown: null,
currentDate: new Date().getTime()
currentDate: getTimeZonedDate(new Date(), this.timeZone).getTime()
};
},
created() {
Expand Down Expand Up @@ -59,10 +59,10 @@ export default {
},
computed: {
convertedFrom() {
return new Date(this.from.toLocaleString("en-US", { timeZone: this.timeZone }));
return getTimeZonedDate(this.from, this.timeZone);
},
formattedTo() {
return new Date(this.to.toLocaleString("en-US", { timeZone: this.timeZone }));
return getTimeZonedDate(this.to, this.timeZone);
},
shouldShowContent() {
return this.currentDate >= this.convertedFrom.getTime() && this.currentDate <= this.formattedTo.getTime();
Expand All @@ -77,7 +77,7 @@ export default {
this.checkDatesValidity();
this.countdown = setInterval(() => {
this.currentDate = new Date().getTime();
this.currentDate = getTimeZonedDate(new Date(), this.timeZone).getTime();
this.checkDatesValidity();
}, 1000);
},
Expand Down
18 changes: 18 additions & 0 deletions src/utils/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,21 @@ export function isValidTimeZone(timeZone) {
export function isValidDate(date) {
return date instanceof Date && !isNaN(date.valueOf());
}

/**
* @param {Date} date
* @param {string} timezone
*
* @return Date
* */
export function getTimeZonedDate(date, timezone) {
if (!isValidDate(date)) {
throw new Error("Invalid date");
}

if (!isValidTimeZone(timezone)) {
throw new Error("Invalid timezone");
}

return new Date(date.toLocaleString("en-US", { timeZone: timezone }));
}

0 comments on commit 6ae354f

Please sign in to comment.