How to get a specific part of moment.js / timezone.js date - javascript

I am quite low at javascript. I started to use moment.js library for my project to make javascript code to work by time & date, which always aligned by specific time zone. But I am struggling to understand how access different parts of my variable. My code:
var ItalyZone = "Europe/Rome";
var currentTime= moment().tz(ItalyZone).format();
alert(currentTime.hours()); //this is not working....
How can access only hours/minutes of that variable "currenTime" ?
How to set new hours for that variable "currentTime" ?
Using simple javascript Date() function I could do simply currentTime.getHours() / currentTime.setHours(), but how should I do using moment.js ???

Why use format when you just want the hours, return a date object instead
var ItalyZone = "Europe/Rome";
var currentTime = moment().tz(ItalyZone).toDate(); // return JS date object
var hours = currentTime.getHours()

You can use the get-set function to do this
moment().minute(Number);
moment().minute(); // Number
moment().minutes(Number);
moment().minutes(); // Number
Gets or sets the minutes.

You can use date format to get any part of date time:
var ItalyZone = "Europe/Rome";
moment().locale(ItalyZone).format("yyyy"); // year
moment().locale(ItalyZone).format("MM"); // month
moment().locale(ItalyZone).format("DD"); // day
moment().locale(ItalyZone).format("hh"); // hours
moment().locale(ItalyZone).format("mm"); // minutes
moment().locale(ItalyZone).format("ss"); // seconts
console.log(moment().locale(ItalyZone).format("YYYY MM DD hh mm ss"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

Related

Compare time with date in express

I want to compare two dates with time and i want if time difference more than one minute then expire message should display otherwise verify message should display.How can i do this here is my code
var dateFormat = require('dateformat');
var day=dateFormat(new Date(date), "yyyy-mm-dd h:MM:ss"); //2018-08-01 11:02:27
var currenttime=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss"); //2018-08-01 11:08:48
var compare = day - currenttime;
console.log(compare);
Using a JavaScript Date object you can use Date.valueOf() to get the milliseconds from the epoch of that time and then do plain subtraction to get the difference. If it is greater than 60000 then expire.
// I swapped your values on either side of the subtraction operator
// to prevent a negative time difference
var compare = currentTime.valueOf() - day.valueOf()
var isExpired = compare >= 60000
console.log('isExpired', isExpired)
You can compare after generating timestamp of both time. Few ways to generate timestamp
1) +new Date()
2) https://momentjs.com/
Example using moment js :
var compare = moment().format('X') - moment("1995-12-25").format('X'); // In seconds

Changing date format javascript

I'm pulling some data from two different APIs and I want to the objects later on.
However, I'm getting two different date formats: this format "1427457730" and this format "2015-04-10T09:12:22Z". How can I change the format of one of these so I have the same format to work with?
$.each(object, function(index) {
date = object[index].updated_at;
}
Here's one option:
var timestamp = 1427457730;
var date = new Date(timestamp * 1000); // wants milliseconds, not seconds
var dateString = date.toISOString().replace(/\.\d+Z/, 'Z'); // remove the ms
dateString will now be 2015-03-27T12:02:10Z.
Try moment.js
var timestamp = 1427457730;
var date = '2015-04-10T09:12:22Z';
var m1 = moment(timestamp);
var m2 = moment(date);
console.log(m1);
console.log(m2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
You can use .format() method in moment to parse the date to whatever format you want, just like:
m2.format('YYYY MMM DD ddd HH:mm:ss') // 2015 Apr 10 Fri 17:12:22
Check out the docs for more format tokens.
What you probably want in javascript, are date objects.
The first string is seconds since epoch, javascript needs milliseconds, so multiply it by 1000;
The second string is a valid ISO date, so if the string contains a hyphen just pass it into new Date.
var date = returned_date.indexOf('-') !== -1 ? returned_date : returned_date * 1000;
var date_object = new Date(date);
Making both types into date objects, you could even turn that into a handy function
function format_date(date) {
return new Date(date.indexOf('-') !== -1 ? date : date * 1000);
}
FIDDLE
Take a look at http://momentjs.com/. It is THE date/time formatting library for JavaScript - very simple to use, extremely flexible.

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);

Timestamp conversion clarification

I created a jsfiddle here
e.onclick=timeConverter('2014-05-02 22:03:34'); //IF I PASS THIS STRING AS DATE, I GOT THIS: 2,May 2014 22:3:34
e.onclick=timeConverter('2014-05-02T22:03:34.890Z'); //IF I PASS THIS STRING AS DATE, I GOT THIS: 3,May 2014 6:3:34
Does "T" or "Z" in the string matters? If someone can enlighten me, thank you.
HTML:
<input type="button" id="format" value="Format Date">
Javascript:
function timeConverter(UNIX_timestamp){
var s = new Date(UNIX_timestamp).getTime()/1000;
var a = new Date(s*1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
//var time = date+','+month+' '+year+' '+hour+':'+min+':'+sec ;
alert(time);
}
var e = document.getElementById('format');
e.onclick=timeConverter('2014-05-02 22:03:34');
//e.onclick=timeConverter('2014-05-02T22:03:34.890Z');
Check this document here which is a extract of ISO 8601.
'T' is just meant as separator between Time and Date.
'Z' is a special indicator for UTC (+00:00) as time zone
The Problem is, '2014-05-02 22:03:34' is kinda chrome specific formatting as far as i know, which treats this time as your local time. So the difference of exactly 8 hours appear.
So to be on the safe side, always remember to put the Separator in and keep in mind what timezone you are referring to.
see this wiki-article , the Z in your string means that you are using the
local timezone, so thats the reason for the differnce in your alert
According to ECMA-262, accepted datetime format is:
[+YY]YYYY[-MM[-DD]][THH:mm[:ss[.sss]]]Z
Where Z is either Z or + , - followed by HH:mm. If you specify Z at the end of your timestamp, it means the time is in UTC. Since you are living in GMT+8, your browser adds 8 hours to convert it to local time. Therefore, you get 3,May 2014 6:3:34 instead of 2,May 2014 22:3:34.

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