Usually our server-side time uses UTC format, which avoids the effect of the server's time zone on the final time. While the client needs to display local time according to the specific timezone, this article describes how to set the server's UTC (Web service implementation based on the ASP. NET Web API) with the client's local (ionic-based hybrid APP) to convert each other.
1. Convert UTC time to local time
Scenario: Typically, the server's data is converted to cost data after the request is finished.
When you define a filter in service, you need to pass in a single parameter: a time string in UTC format and a conversion format.
. Filter (' utctolocal ', function utctolocal ($filter) { return function (utcdatestring, format) { if (! utcdatestring) { return; } if (Utcdatestring.indexof (' z ') = = =-1 && utcdatestring.indexof (' + ') = = =-1) { utcdatestring + = ' z '; } return $filter (' Date ') (utcdatestring, format);} ; })
Use filter in the page:
<p>{{item.triggeredtimestring|utctolocal: "Yyyy-mm-dd HH:mm:ss"}}</p>
How to use it in directives? The utctolocal function needs to be redefined, called as follows. Note: You need to declare $filter at the root directive.
var utctolocal = function (utcdatestring) { if (!utcdatestring) { return; } if (Utcdatestring.indexof (' z ') = = =-1 && utcdatestring.indexof (' + ') = = =-1) { utcdatestring + = ' z '; } return $filter (' Date ') (Utcdatestring, "Yyyy-mm-dd HH:mm:ss"); } $filter (' Date ') (Utcdatestring, "Yyyy-mm-dd HH:mm:ss");
2. Convert local time to UTC time
Scenario: used when the service is typically called to send data.
2.1 Defines a function that uses the UTC date constructor to generate UTC time.
var toutcdate = function (date) { var _utc = new Date (Date.getutcfullyear (), Date.getutcmonth (), Date.getutcdate (), C1/>date.getutchours (), Date.getutcminutes (), date.getutcseconds ()); return _UTC; }; var localtime = new Date (); var utctime = toutcdate (localtime); $log. info (localtime); $log. info (utctime);
2.2 Directly using Library functions toutcstring:
var localtime = new Date (), var UTC = Localtime.toutcstring ();
2.3 Using Moment.js:
var localtime = new Date ();
MOMENT.UTC (localtime);
Resources:
Http://stackoverflow.com/questions/31778624/converting-local-time-into-utc-time-in-angularjs
Https://github.com/urish/angular-moment
Http://stackoverflow.com/questions/31785364/converting-date-from-local-time-zone-to-utc-and-then-to-local
19th: Interchange of UTC time and local time