Moment.js not displaying local Date and Time format - javascript

I am trying to display a time stamp for the user if a comment was older than 24 hours. The following code does that but it is still showing my (US) date and time format for my developers in Pakistan. Instead of mm/dd/yy it should display dd/mm/yy. Any reason why it is not working correctly? Here is my code.
//get date of comment
let commentDateUTC = item.createdOn;
//convert it to local time
let commentLocalTime = moment.utc(commentDateUTC).local().toLocaleString();
//determine amount of time elapsed between comment and current time
let nowObj = { 'now': moment(commentLocalTime).fromNow() }
//determine if more than 24 hours has elapsed since the comment was created
let currentTime = moment().local().toLocaleString();
let elapsedTime = moment(currentTime).diff(commentLocalTime, 'hours');
//if yes, concatenate the item.createdOn and the nowObj.now value
if (elapsedTime >= 24) {
nowObj.now = `${moment(commentLocalTime).format('l LT')} (${nowObj.now})`
}

This is the answer. You have to grab the locale from the browser settings and then set it using moment.locale();. I wish the docs were a little more clear on this....
if (elapsedTime >= 24) {
var locale = window.navigator.language;
moment.locale(locale);
nowObj.now = `${moment(commentLocalTime).format('l LT')} (${nowObj.now})`
}

Related

Adding "HH:MM" time format to Date Object Javascript properly

I have the requirement to set particular time of the day to Date Object. The Time is in String and is CET, so "16:00" means "15:00" in UTC in Winter time. The following code does the job in node.js on my local machine which is in CET Timezone:
addTimetoDate(new Date(),"16:00");
function addTimetoDate(theDate,theTime){
var dtDate = new Date(theDate)
try{
var strTime = theTime.replace(/ /g,'');
var hourArray = strTime.split(":");
dtDate.setHours(parseInt(hourArray[0]), parseInt(hourArray[1]), 0)
if (dtDate == "Invalid Date"){
dtDate = theDate;
}
} catch (e){
dtDate = theDate;
}
return dtDate
}
However when deployed to remote server it produces Date Object which is offset by one hour the other direction when displayed with toLocaleString it shows "17:00".
How to do it elegant way (as simple deduction of one hour will work only in Winter Time.
---EDIT---
To clarify the question is - Is there anything I can do prior to using .setHours to make it right. Or I should not use setHours but rather manipulate the string for Date Constructor, so 16.00 CET gets properly converted to UTC representation?
toLocaleString will convert the given time into the timezone defined by the locale,... and that's fine if the time is UTC to start with. But if it's already been offset, then it's going to offset it again, which is what you're seeing.
Time is a fiddly creature; when I'm working with time I always store it (eg in a database) as UTC and let the client descide how it gets displayed. That way I can guarantee no server-side silliness.
Ok Found the solution:
function addTimetoDate(theDate,theTime){
var d = new Date();
var hourLocal = d.toLocaleString({timezone:'Europe/Berlin'}).split(" ")[1].split(":")[0]
var hourISO = d.toISOString().split("T")[1].split(":")[0]
var diff = parseInt(hourLocal) - parseInt(hourISO);
var dtDate = new Date(theDate)
try{
var strTime = theTime.replace(/ /g,'');
var hourArray = strTime.split(":");
dtDate.setHours(parseInt(hourArray[0])-diff, parseInt(hourArray[1]), 0)
if (dtDate == "Invalid Date"){
dtDate = theDate;
}
} catch (e){
dtDate = theDate;
}
return dtDate
}
Diff in whatever situation - being on the server, or on the browser captures current status (including daylight saving change) of hourly difference for the given Timezone. Then you can adjust your given hour to UTC to use setHours.

JavaScript Date object in another time zone, how to render office hours? [duplicate]

This question already has an answer here:
new Date() for a specific timezone in JavaScript
(1 answer)
Closed 5 years ago.
This seemed fairly trivial but I might be over-thinking it.
I would like to render my chat widget between 9AM(PST) and 5PM(PST) mon-fri
Using new Date() always puts time into the browsers time zone. Basically i need to instantiate a date in PST and check if between days and hours.
var d = new Date();
var day = d.getDay();
var hour = d.getHours();
if (day > 0 && day < 6 && hour > 9 && hour < 17) {
renderChatWidget($('#chat-widget')):
}
I think this is incorrect because it uses the browser time, so if its 9:30AM in London then PST time would be like 2am and it would still render the chat widget...
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time for "+ city +" is "+ nd.toLocaleString();
}
document.getElementById('title').innerHTML=(calcTime('California', '-7'));
<h1 id="title">Time Zone Example</h1>
This is from this post and I just turned it into a snippet to see it work. You can then use the modified (correct) date through your tests using the correct time zone.
You can use UTC time.
var current_time = new Date;
var utc_time = Date.UTC(
current_time.getUTCFullYear(),
current_time.getUTCMonth(),
current_time.getUTCDate() ,
current_time.getUTCHours(),
current_time.getUTCMinutes(),
current_time.getUTCSeconds(),
current_time.getUTCMilliseconds());

Date format with time range in javascript

I have a javascript date variable as 04/05/2015, 01:30 (dd/mm/yyyy, HH:mm) format. Now how can I change that format to 04/05/2015, 01:00-01:30 format. Ie, I want to change the time with time range where the first time value is always 30 minutes less than second time value. So If the date is 04/05/2015, 13:00 then the formatted date would be 04/05/2015, 12:30-13:30
EDIT: See the fiddle here for the sample.
Please check the below solutions:
http://jsfiddle.net/ub942s6y/14/
You need to change data.addColumn('datetime', 'Date'); to 'string' as we are changing time
It will work fine. :)
Im affraid that there is no out-of-the-box functionality for what you are asking, and you will have to write your own function for that.
Here is a js Date object specification : Date Object
Your new function return type cannot be Date, as this kind of formatting can be only achieved with string type.
You can't have date object in that format. You will have manually create the format. It will be string.
var dateObj = new Date('04/05/2015, 01:30'), // input date
interval = 30, // interval in minutes
remainingInterval = 0;
var hours = dateObj.getHours(),
minutes = dateObj.getMinutes();
if(minutes > interval) {
minutes = minutes - interval;
} else {
remainingInterval = interval - minutes;
minutes = 60;
hours = hours - 1;
minutes = minutes - remainingInterval;
}
resulting date can be
console.log(dateObj.getDate()+'/'+dateObj.getMonth()+'/'+dateObj.getFullYear()+', '+dateObj.getHours()+':'+dateObj.getMinutes()+' - '+hours+':'+minutes);

How to check condition on time

Hi i want to put condition on time that only time between 9:00 AM to 5:00 PM has to access.
here is my javascript code for it.
var time = document.getElementsByName('s_time')[0].value;
if user enter tie before 9:00 AM or after 5:00 PM it should give alert. Please help me
User enterd time by using jquery picker.
This is not complete solution, But hope this will help you
Get current time Get in milliseconds,
the time difference between
next execution time minus current time Settimeout with result
millisecons
Here is simple example
You just need to calculate the difference between the current time and the target time and use setTimeout() with that value.
For example, depending on how your target browsers parse dates, you could do the following:
function alert3pm() {
alert("It's 3PM!");
}
var timeAt3pm = new Date("1/31/2011 03:00:00 PM").getTime()
, timeNow = new Date().getTime()
, offsetMillis = timeAt3pm - timeNow;
setTimeout(alert3pm, offsetMillis);
Or rather, instaed of parsing a date (since that's really inconsistent between browsers) you could do something like this:
function getTimeAtHour(hour) {
var t = new Date();
t.setHours(hour);
t.setMinutes(0);
t.setSeconds(0);
t.setMilliseconds(0);
return t;
}
http://www.w3schools.com/jsref/jsref_obj_date.asp
var time = document.getElementsByName('s_time')[0].value || new Date().getTime();
var d = new Date(time);
var currentHour = d.getHours();
if (currentHour < 9 || currentHour >= 17) {
alert('something');
}

Convert UTC time to specific zone

I have the following data:
var currentTime: 2013-07-11 15:55:36+00:00
var currentTimezone: Africa/Asmera
I need a way to convert the currentTime in UTC to a new time based on currentTimezone.
I've looked into Timezone.js and I'm having trouble implementing it (the directions on the site are a little ambiguous)
The code for the function I'm intending on using is included. Thanks :)
<script>
$("#storeTime").click(function(){
storeCurrentTime();
})
$("#getTime").click(function(){
retrieveTime();
})
$("#storeTimezone").click(function(){
var yourTimezone = $('#timezone-select').find(":selected").text();
tz = yourTimezone.toString();
storeCurrentTimezone(tz);
})
$("#convertTime").click(function(){
//get the most recent UTC time, clean it up
var currentTime = $('#RetrievedTime').html();
currentTime = currentTime.split(": ")[1];
$('#convertedTime').html("Converted Time: " + currentTime);
//get the saved timezone
var currentTimezone = $('#storedTimezone').html();
})
</script>
You're going to need to know the timezone offset, so some sort of dictionary with strings to numbers.
// assuming your dictionary says 3 hours is the difference just for example.
var timezoneDiff = 3;
Then you can just make a new time like this
// Assuming you have the proper Date string format in your date field.
var currentDate = new Date(currentTime);
// Then just simply make a new date.
var newDate = new Date(currentDate.getTime() + 60 * 1000 * timezoneDiff);
Update
I've written a javascript helper for this which you can find at:
http://heuuuuth.com/projects/OlsonTZConverter.js
I pulled the timezone data from the wikipedia page https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Usage is as follows once included the script.
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera");
or if there is Daylight Savings in effect:
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera",true);
These will throw if you pass an invalid timezone, but you can check if a timezone is valid with:
var isValid = OlsonTZConverter.Contains("Africa/Asmera");
or just look at the entire dictionary with:
var tzDict = OlsonTZConverter.ListAllTimezones();
Hope this maybe saves someone some time sometime :).

Categories