Converting from time to timestamp in moment js? - angularjs

I am using ionic time picker in my app and when a time is selected from this plugin it gives the timestamp in callback.
For ex : if time selected is 09:30 AM the timestamp in callback is 34200 and to convert this timestamp to its original value i.e 09:30 AM I am doing this
moment.unix(callback).utc().format('hh:mm A');
now I have to reverse this i.e I have time as 09:30 AM and I want to get timestamp from it as 34200 using moment js.
How can I do that.

The UNIX timestamp 34200 its basically the date 1970-01-01 09:30 AM so to convert it back you need to set the correct date since this information is lost when you format using hh:mm A.
var callback = 34200;
var asHHMM = moment.unix(callback).utc().format('hh:mm A');
var asUNIX = moment.utc(asHHMM, 'hh:mm A').year(1970).month(0).date(1).unix();
console.log(callback, asHHMM, asUNIX);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Related

How Can I Set Global Timezone and Change Time in React?

How can I set the time zone globally in react? Is it possible? I know the new Date() of javascript actually gives the time zone of the system. But I want to set the time zone in one file in react application and re use it. And when I will change the time, the time will also be changed according to the specific time zone. Thanks in advance.
Hey this is not a react related question, I would say more of a JS question but what I normally do is to use Luxon, you need to install the library an afterwards what I do is this:
// src/utils/luxon/index.ts
import {DateTime, Settings} from 'luxon'
// Example to set EST as the default timezone in the app.
Settings.defaultZoneName = 'America/New_York'
export {DateTime, Settings}
Then I just import that utils file and use the DateTime object to parse and handle dates.
So if you have lets say for example an epoch date you can parse it like this
import {DateTime} from 'utils/luxon'
const epochDate = 1597354080
const luxonDate = DateTime.fromSeconds(epochReleaseDate)
console.log(luxonDate.toLocaleString(DateTime.TIME_SIMPLE))
If you click this page you will notice that the current est time for that epoch should return Thursday August 13, 2020 17:28:00 (pm)
You can parse those dates to Javascript date objects but I suggest you to get used to luxon because it makes working with dates pretty easy. Just remember that the Date returned by luxon is way different than the Js Date object so don't combine them, instead use the parsing methods of luxon to convert a Js Date to Luxon Date and vice versa
I actually tried to solve the problem this way. to initialize the date in the ui I called the getGlobalDate function instead of calling new Date() in js. And for changing the date I passed the date object to onChangeFormat function and convert the date time.
export const language = "en-US";
export const timeZone = { timeZone: "Pacific/Auckland" };
//to initialize the date
export function getGlobalDate() {
return new Date().toLocaleString(language, timeZone);
}
//for onChanging the date and convert it to the timzone
export function onChangeFormat(e) {
const convertToUTC = e.toLocaleString(language, timeZone);
console.log(convertToUTC);
return convertToUTC;
}

angular-pickadate timezone - selectedDate is one day before from modal date for other timezones

angular-pickadate works for my local time. To check global Times, I have changed my time zone to "America/Denver". Now selected date is taken one day before today's date (passed modal date), so it applies "pickadate-active" class to yesterday.
I tried passing modal date with local timezone and also with UTC timezone. I don't know why dateHelper.parseDate calls again with stripping Timezone value earlier passed, now my understanding is $locale is converting stripped date assuming it a UTC date to local date. Hence, being GMT-06:00, selected date comes to one date before.
HTML DIV - <div pickadate ng-model="vm.date" ng-model-options="{ debounce: 0 }" header="true" select="true" date-highlight-list="vm.dateList" ></div>
Controller - vm.date = moment().tz(timeZoneName).format();
can someone suggest a way to handle different timezones with angular-pickadate?? Thanks !
GIT directive URL - https://github.com/restorando/angular-pickadate
The parseDate function was giving date object as per GMT timezone, so date was becoming one day less.So I removed this condition which was directly returning GMT date for passed date strings with timezone.
if (angular.isDate(dateString) || angular.isDate(new Date(dateString))) {
new Date(dateString); }
Now it goes to next if block to format date with regex and added this condition there to handle date strings and date objects -
if(typeof dateString == 'object') {
dateString = (dateString['_d'])? dateString['_d']: dateString['_i']; // being private (_d, _i) should be avoided but only way in mine case
if(typeof dateString == 'object') // returns Object by dateString['_d'] else string
dateString = dateString.getDate() +'-'+ dateString.getMonth() +'-' +dateString.getFullYear();
}
dateParts = dateString.split(separator); // separator was "-" every time so making dateString with "-" in case it was object

converting date format in angularjs controller

i write the following coding to print the current date time
$scope.date = new Date();
and then i print the same using consol.log
console.log($scope.date);
and it is working fine
Tue Jan 24 2017 16:36:06 GMT+0530 (India Standard Time)
but now i want to change the date format and i want to print like
21-12-2016
can anybody help me here?
i used the conversion but i am unable to remember the page or the url of the page right now,
and stuck on this,
before i leave for the home today i thought of solving this issue
In controller you can do
$filter('date')(date, format, timezone)
to change the date format. And in html,
{{ date_expression | date : format : timezone}}
use this.
Like
$scope.formattedDate = $filter('date')($scope.currDate, "dd-MM-yyyy");
to print same on html
{{ currDate | date : "dd-MM-yyyy"}}
https://docs.angularjs.org/api/ng/filter/date
Following formats are supported by angular.
You can do this either in controller or in html page.
$scope.date = new Date();
The first one is :
$scope.date = $filter('date')($scope.date, 'dd-MM-yyyy');
Second one is :
{{date | date:'dd-MM-yyyy'}}
You can use the Angular date filter:
{{date | date: 'dd-MM-yyyy'}}
You can use the in-build js libraries functions i.e getDay(), getHours(), getMinutes(), getMilliseconds(). This functions will return you the corresponding date's individual components values.
e.g
var x = $scope.yourDateModelObj.getHours();
Likewise, you can get the date, month, years values.
return an integer value for hours.
Hope that helps

Angular show wrong time with unknown timezone

flight.departure_at is a UTC format 2016-05-04T19:00:00.000Z
When I display this expression in the page,
It's format is totally out of expectation.
Why does the 12:00 come out? How come?
I also want to know how could I keep all the time format in UTC globally without adding options everywhere. It will make the whole App vulnerable
code
Departure_time: {{flight.departure_at}} ||| {{flight.departure_at | date: 'HH:mm'}}
output
Departure_time: 2016-05-04T19:00:00.000Z ||| 12:00
This standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ
'T' is just a separator between date and time in ISO-8601 format.
'Z' is zero time zone ( your getting 12:00 , because it convert to your timezone)
we can use parse like this ,
var date = new Date('2016-05-04T19:00:00.000Z');
console.log(date.getUTCHours()); // Hours - 19
console.log(date.getUTCMinutes()); //0
console.log(date.getUTCSeconds());// 0
console.log(Date.parse(date));
console.log(new Date(Date.parse(date)));
OR
Date.parse(DATE) for getting time in standard time format
UTC
As stated in a different thread about personalizing timezones to the user - I've found this to be very helpful when coming to dealing with timezones in Angular. (https://stackoverflow.com/a/35161107/3585278)
module.config(['$provide', function($provide) {
var DEFAULT_TIMEZONE = 'GMT';
$provide.decorator('dateFilter', ['$delegate', '$injector', function($delegate, $injector) {
var oldDelegate = $delegate;
var standardDateFilterInterceptor = function(date, format, timezone) {
if(angular.isUndefined(timezone)) {
timezone = DEFAULT_TIMEZONE;
}
return oldDelegate.apply(this, [date, format, timezone]);
};
return standardDateFilterInterceptor;
}]);
}]);
I suggest you use Angular moment for all date time related stuff for the frontend and moment for the controller part.
You should store all time as UTC in backend and then on frontend you can set user's timezone globally as
app.constant('angularMomentConfig', {
'timezone' : <user's timezone>
});
Render UTC time now on frontend without worrying about timezone(make sure all variables are either moment or Date object):
<td ng-bind="flight.departure_at| amDateFormat:'HH:mm'"></td>

How to get local date with Timezone(EDT/PST) in Angular JS using moment?

I want the current local(to browser) date with Time zone in the following format:
26-Apr-2016 15:56:18 EDT
I have tried using moment.js but it shows date with timezone like GMT -04:00. Also tried this, but it didn't help.
var dateDDMMMYYYYFormate = $filter('date')(new Date(input), 'dd-MMM-yyyy HH:mm:ss');
var dateWithUtc = moment.utc(dateDDMMMYYYYFormate);
var localDate = moment(dateWithUtc).local();
Any help is appreciated.
Since new Date() creates a JavaScript date object, you want to change the moment object into a date object:
var localDate = moment().toDate();

Resources