diff --git a/Directory.Packages.props b/Directory.Packages.props index 0af612b056..0a243a3067 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -177,7 +177,7 @@ - + diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/auth-list-utc1.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/auth-list-utc1.png new file mode 100644 index 0000000000..9adbd41062 Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/auth-list-utc1.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/auth-list-utc3.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/auth-list-utc3.png new file mode 100644 index 0000000000..51256b2d62 Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/auth-list-utc3.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/auth-list.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/auth-list.png new file mode 100644 index 0000000000..cc0a92b591 Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/auth-list.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/berlin.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/berlin.png new file mode 100644 index 0000000000..07715caabd Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/berlin.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/blazor-create.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/blazor-create.png new file mode 100644 index 0000000000..5385c14167 Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/blazor-create.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/blazor-edit.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/blazor-edit.png new file mode 100644 index 0000000000..95c0357171 Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/blazor-edit.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/blazor-list.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/blazor-list.png new file mode 100644 index 0000000000..181983492c Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/blazor-list.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-create.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-create.png new file mode 100644 index 0000000000..827e8911d7 Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-create.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-edit.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-edit.png new file mode 100644 index 0000000000..a3cc8a6a0c Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-edit.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-list-utc1.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-list-utc1.png new file mode 100644 index 0000000000..9904c56df5 Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-list-utc1.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-list-utc3.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-list-utc3.png new file mode 100644 index 0000000000..7d472296fb Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-list-utc3.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-list.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-list.png new file mode 100644 index 0000000000..282f288855 Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-list.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-post.png b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-post.png new file mode 100644 index 0000000000..35bff4aded Binary files /dev/null and b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/mvc-post.png differ diff --git a/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/post.md b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/post.md new file mode 100644 index 0000000000..bfde4d5318 --- /dev/null +++ b/docs/en/Community-Articles/2025-03-11-Developing-A-Multi-Timezone-Application-Using-The-ABP-Framework/post.md @@ -0,0 +1,779 @@ +# Developing a Multi-Timezone Application Using the ABP Framework + +When developing multi-timezone applications, we need to handle users from different time zones and make sure they see the correct time. The system also needs to support users changing their timezone (like when traveling or moving) and make sure all time displays update correctly to show accurate time information. + +All these scenarios require us to handle timezone conversions correctly in our application. The ABP framework provides a complete solution for these challenges. + +In this article, we'll show you step by step how to handle multi-timezone in the ABP framework. + +## Timezone Settings + +The ABP framework provides a setting called `Abp.Timing.TimeZone` for setting and getting the timezone of users, tenants, or applications. The default value is empty, which means the application will use the server's time zone. Check out the [Timing documentation](https://abp.io/docs/latest/framework/infrastructure/timing) for more information. + +## ISO 8601 Date Time Format + +Different countries and regions may use different time formats: + +* Year-Month-Day (YYYY-MM-DD): Mainly used in China, Japan, Korea, Canada (official standard), Germany (ISO standard), ISO 8601 international standard, etc. Example: 2025-03-11 +* Day-Month-Year (DD-MM-YYYY): Mainly used in UK, India, Australia, New Zealand, most European countries (like France, Germany, Italy, Spain), some South American countries, etc. Example: 11-03-2025 or 11/03/2025 +* Month-Day-Year (MM-DD-YYYY): Mainly used in USA, Philippines, some parts of Canada, etc. Example: 03-11-2025 or 03/11/2025 +* Day.Month.Year (DD.MM.YYYY): Mainly used in Germany, Russia, Switzerland, Hungary, Czech Republic, etc. Example: 11.03.2025 + +Also, different countries/regions might use different separators (like slash /, hyphen -, dot .), and some countries use different month abbreviations or full names (like March 11, 2025). + +ISO 8601 uses a standard format to avoid confusion between different date formats and ensure global compatibility. + +It has 4 parts: + +* Date part: `YYYY-MM-DD` +* `T` as a separator +* Time part: `HH:MM:SS` +* Timezone part: `Z` or `+/-HH:MM` + +You'll usually see formats like: `YYYY-MM-DDTHH:MM:SSZ` or `YYYY-MM-DDTHH:MM:SS+/-HH:MM`, for example: `2025-03-11T10:30:00Z` or `2025-03-11T22:30:00+03:00` + +When our application needs to handle multiple timezones, we usually use ISO 8601 to represent time. + +## Enabling Multi-Timezone Support + +When we set the `Kind` of `AbpClockOptions` to `DateTimeKind.Utc`, the ABP framework will normalize all times. Times written to the database and returned to the frontend will be in `UTC`. the `SupportsMultipleTimezone` property will be `true` in the `IClock` service. + +```csharp +Configure(options => +{ + options.Kind = DateTimeKind.Utc; +}); +``` + +### Using DateTime to Store Time + +Assuming the `DateTime` stored in the database is `2025-03-01 10:30:00`, then the time returned to the front end will be `2025-03-01T10:30:00Z`. This is a time in ISO 8601 format. Because `DateTime` does not have timezone information, the framework will assume it is `UTC` time. + +### Using DateTimeOffset to Store Time + +If you use `DateTimeOffset` to store time, the ABP framework will not normalize `DateTimeOffset`, but will return it directly to the front end. + +Assuming the `DateTimeOffset` stored in the database is `2025-03-01 13:30:00 +03:00`, then the time returned to the front end will be `2025-03-01T13:30:00+03:00`. This is also a time in ISO 8601 format. + +We recommend using `DateTimeOffset` to store time because it has timezone information. + +## Timezone Conversion + +### Converting UTC Time to User Time + +The `IClock` service has 2 methods to convert a given `UTC` time to the user time: + +```csharp +DateTime ConvertToUserTime(utcDateTime dateTime) +DateTimeOffset ConvertToUserTime(DateTimeOffset dateTimeOffset) +``` + +> If `SupportsMultipleTimezone` is `false` or `dateTime.Kind` is not `Utc` or no timezone is set, it will return the given `DateTime` or `DateTimeOffset` without any changes. + +**Example:** + +If the user's timezone is `Europe/Istanbul` + +```csharp +// 2025-03-01T05:30:00Z +var utcTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc); + +var userTime = Clock.ConvertToUserTime(utcTime); + +// Europe/Istanbul has 3 hours difference with UTC. So, the result will be 3 hours later. +userTime.Kind.ShouldBe(DateTimeKind.Unspecified); +userTime.ToString("O").ShouldBe("2025-03-01T08:30:00"); +``` + +```csharp +// 2025-03-01T05:30:00Z +var utcTime = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc), TimeSpan.Zero); + +var userTime = Clock.ConvertToUserTime(utcTime); + +// Europe/Istanbul has 3 hours difference with UTC. So, the result will be 3 hours later. +userTime.Offset.ShouldBe(TimeSpan.FromHours(3)); +userTime.ToString("O").ShouldBe("2025-03-01T08:30:00.0000000+03:00"); +``` + +### Converting User Time to UTC + +The `IClock` service has 1 method to convert a given user time to UTC. + +```csharp +DateTime ConvertToUtc(DateTime dateTime) +``` + +> If `SupportsMultipleTimezone` is `false` or `dateTime.Kind` is `Utc` or no timezone is set, it will return the given `DateTime` without any changes. + +**Example:** + +If the user's timezone is `Europe/Istanbul` + +```csharp +// 2025-03-01T05:30:00 +var userTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified); //Same as Local + +var utcTime = Clock.ConvertToUtc(userTime); + +// Europe/Istanbul has 3 hours difference with UTC. So, the result will be 3 hours earlier. +utcTime.Kind.ShouldBe(DateTimeKind.Utc); +utcTime.ToString("O").ShouldBe("2025-03-01T02:30:00.0000000Z"); +``` + +## Handling Timezone in Different UIs + +We'll use the `TimeZoneApp` project to demonstrate handling timezone in different UIs. It has a `Meeting` entity, with several time properties. + +```csharp +public class Meeting : AggregateRoot +{ + public string Subject { get; set; } + + public DateTime StartTime { get; set; } + + public DateTime EndTime { get; set; } + + public DateTime ActualStartTime { get; set; } + + public DateTime? CanceledTime { get; set; } + + public DateTimeOffset ReminderTime { get; set; } + + public DateTimeOffset? FollowUpTime { get; set; } + + public string Description { get; set; } +} +``` + +`TimeZoneApp` project is an ABP layered architecture project, it sets a global `Europe/Istanbul` timezone, it contains 4 websites + +* `API.Host`: API website, it does not have UI, it returns data in JSON format +* `AuthServer`: Authentication server, it uses Razor Pages as UI +* `Web`: Razor Pages website, it uses JavaScript to manage Meeting creation and editing and display +* `Blazor`: Blazor Server website, it uses Blazor to manage Meeting creation and editing and display + +All 4 applications are enabled for multi-timezone support, and use the `UseAbpTimeZone` middleware. + +> Blazor WASM and Angular do not need to use the `UseAbpTimeZone` middleware + + +### DateTime in API Response + +In the API response, we usually use the ISO 8601 format time, as you can see, after enabling multi-timezone support, the API returns time to the front end as UTC time. + +`2025-03-01T09:30:00Z` and `2025-03-01T12:30:00+00:00` are ISO 8601 format time. + +```json +[ + { + "subject": "ABP Developer Guide", + "startTime": "2025-03-01T09:30:00Z", + "endTime": "2025-03-01T10:30:00Z", + "actualStartTime": "2025-03-01T11:30:00Z", + "canceledTime": null, + "reminderTime": "2025-03-01T12:30:00+00:00", + "followUpTime": "2025-03-01T13:30:00+00:00", + "description": "We will discuss the ABP developer guide.", + "id": "2af0abd3-be06-ecff-5d4c-3a1895ac7950" + }, + { + "subject": "ABP Training", + "startTime": "2025-03-01T09:30:00Z", + "endTime": "2025-03-01T10:30:00Z", + "actualStartTime": "2025-03-01T11:30:00Z", + "canceledTime": "2025-03-01T12:00:00Z", + "reminderTime": "2025-03-01T12:30:00+00:00", + "followUpTime": "2025-03-01T13:30:00+00:00", + "description": "ABP training for the new developers.", + "id": "290b0cb6-3e50-6324-1e79-3a1895ac795f" + } +] +``` + +### Handling Timezone in MVC/Razor Pages + +In the `AuthServer` project, we handle time conversion in a simple way: +1. First, we get the `Meeting` entities from the database using `IRepository`. At this point, all `DateTime` values are in UTC. +2. Then, when displaying the times in the view, we use `Clock.ConvertToUserTime` to show them in the user's timezone. + +> Note: The `ConvertToUserTime` method will only convert times if multi-timezone support is enabled in the application. + +```csharp +public class IndexModel : AbpPageModel +{ + public List? Meetings { get; set; } + + protected IRepository MeetingRepository { get; } + + public IndexModel(IRepository meetingRepository) + { + MeetingRepository = meetingRepository; + } + + public async Task OnGetAsync() + { + Meetings = await MeetingRepository.GetListAsync(); + } +} +``` + +```html +
+ +
+ + + + + + + + + + + + + + @foreach (var meeting in Model.Meetings) + { + + + + + + + + + + } + +
@L["Subject"]@L["StartTime"] / @L["EndTime"]@L["ActualStartTime"]@L["CanceledTime"]@L["ReminderTime"]@L["FollowUpTime"]@L["Description"]
@meeting.Subject@Clock.ConvertToUserTime(meeting.StartTime) ➡️ @Clock.ConvertToUserTime(meeting.EndTime)@Clock.ConvertToUserTime(meeting.ActualStartTime)@(meeting.CanceledTime.HasValue ? Clock.ConvertToUserTime(meeting.CanceledTime.Value) : "N/A")@Clock.ConvertToUserTime(meeting.ReminderTime).DateTime@(meeting.FollowUpTime.HasValue ? Clock.ConvertToUserTime(meeting.FollowUpTime.Value).DateTime : "N/A")@meeting.Description
+
+
+
+``` + +![](auth-list.png) + +### Handling Timezone in JavaScript + +In the `Web` project, we use JavaScript to handle timezone. + +#### Displaying Time in UI + +* `timeZoneApp.meetings.meeting.getList` gets all `Meeting` entities and displays them in `DataTables` +* `abp.clock.normalizeToLocaleString()` is the ABP JavaScript API, it converts `UTC` time to the current user's timezone, and then calls its `toLocaleString` method to format time +* `dataFormat: "datetime"` is the ABP DataTable extension method, it calls the `abp.clock.normalizeToLocaleString` method to convert and format time + +> If the current application is not enabled for multi-timezone support, then the `abp.clock.normalizeToLocaleString` method will not convert the time, it will just call the `Date` object's `toLocaleString` method. + +```js +var dataTable = $('#MeetingsTable').DataTable( + abp.libs.datatables.normalizeConfiguration({ + serverSide: true, + paging: true, + order: [[1, "asc"]], + searching: false, + scrollX: true, + ajax: abp.libs.datatables.createAjax(timeZoneApp.meetings.meeting.getList), + columnDefs: [ + { + title: l('Actions'), + rowAction: { + items: + [ + { + text: l('Edit'), + visible: abp.auth.isGranted('TimeZoneApp.Meetings.Edit'), + action: function (data) { + editModal.open({ id: data.record.id }); + }, + }, + { + text: l('Delete'), + visible: abp.auth.isGranted('TimeZoneApp.Meetings.Delete'), + confirmMessage: function (data) { + return l('MeetingDeletionConfirmationMessage', data.record.subject); + }, + action: function (data) { + timeZoneApp.meetings.meeting + .delete(data.record.id) + .then(function() { + abp.notify.info(l('SuccessfullyDeleted')); + dataTable.ajax.reload(); + }); + } + } + ] + } + }, + { + title: l('Subject'), + data: "subject" + }, + { + title: l('StartTime') + ' / ' + l('StartTime'), + data: "startTime", + render: function (data, type, row) { + return abp.clock.normalizeToLocaleString(row.startTime) + ' ➡️ ' + abp.clock.normalizeToLocaleString(row.endTime); + } + }, + { + title: l('ActualStartTime'), + data: "actualStartTime", + dataFormat: "datetime" + }, + { + title: l('CanceledTime'), + data: "canceledTime", + render: function (data, type, row) { + return data ? abp.clock.normalizeToLocaleString(data) : 'N/A'; + } + }, + { + title: l('ReminderTime'), + data: "reminderTime", + dataFormat: "datetime" + }, + { + title: l('FollowUpTime'), + data: "followUpTime", + render: function (data, type, row) { + return data ? abp.clock.normalizeToLocaleString(data) : 'N/A'; + } + }, + { + title: l('Description'), + data: "description" + } + ] + }) +); +``` + +Below is the screenshot of `DataTables`: + +![](mvc-list.png) + + +#### Creating and Editing Meeting + +We use `JavaScript` to create and edit `Meeting`. + +ABP's [TagHelper](https://abp.io/docs/latest/framework/ui/mvc-razor-pages/tag-helpers) can automatically create forms based on the model, it will generate corresponding HTML tags based on the attributes in the model. For `DateTime` and `DateTimeOffset` attributes, it will generate and initialize a [DateTimePicker](https://www.daterangepicker.com/) component. + +**CreateModal** and **EditModal** : + +```html + + + + + + + + + +``` + +```html + + + + + + + + + + +``` + +You can see that the time in the control has been converted to the current user's timezone. + +![](mvc-create.png) + +![](mvc-edit.png) + +When we submit the form, we need to convert the time to `UTC`. In the `JavaScript` of the `Create` and `Edit` pages, we use the `handleDatepicker` this `jQuery` extension method to handle time in the form, it internally gets the user's local time from the selector `input[type="hidden"][data-hidden-datepicker]`, and then uses the `abp.clock.normalizeToString` method to convert the date field in the form to the `ISO 8601` format `UTC` time string. + +> If the current application is not enabled for multi-timezone support, then the `abp.clock.normalizeToString` method will not convert the time, it will just convert to the ISO 8601 format time string without timezone. + +```js +var abp = abp || {}; +$(function () { + abp.modals.meetingCreate = function () { + var initModal = function (publicApi, args) { + var $form = publicApi.getForm(); + $form.find('button[type="submit"]').on('click', function (e) { + $form.handleDatepicker('input[type="hidden"][data-hidden-datepicker]'); + }); + }; + + return { + initModal: initModal + } + }; +}); +``` + +The requested data is as follows: + +```csharp +Request URL: Meetings/EditModal +Request Method: POST +Payload: + Id: 0803780b-3762-2af8-1c75-3a1895d59c89 + Meeting.Subject: ABP Developer Guide + Meeting.StartTime: 2025-03-01T09:30:00.000Z + Meeting.EndTime: 2025-03-01T10:30:00.000Z + Meeting.ActualStartTime: 2025-03-01T11:30:00.000Z + Meeting.CanceledTime: + Meeting.ReminderTime: 2025-03-01T12:30:00.000Z + Meeting.FollowUpTime: 2025-03-01T13:30:00.000Z + Meeting.Description: We will discuss the ABP developer guide. +``` + +![](mvc-post.png) + +In short, we use the `abp.clock.normalizeToLocaleString` method to display time, and use the `abp.clock.normalizeToString` method to modify the time to be submitted. If you submit data via `ajax`, please remember to use the `abp.clock.normalizeToString` method to convert time. + +### Handling Timezone in Blazor + +We cannot automatically complete some work in `Blazor UI`, we need to inject `IClock` and use the `ConvertToUserTime` and `ConvertToUtc` methods to display and create/update entities. + +Below is a complete `Meeting` page, please refer to the usage of `Clock` in it. + +```csharp +@page "/meetings" +@using Volo.Abp.Application.Dtos +@using Microsoft.Extensions.Localization +@using TimeZoneApp.Meetings +@using TimeZoneApp.Localization +@using TimeZoneApp.Permissions +@using Volo.Abp.AspNetCore.Components.Web +@inject IStringLocalizer L +@inject AbpBlazorMessageLocalizerHelper LH +@inherits AbpCrudPageBase + + + + + +

@L["Meetings"]

+
+ + @if (HasCreatePermission) + { + + } + +
+
+ + + + + + + + + + + + + + + @Clock.ConvertToUserTime(context.StartTime).ToString("yyyy-MM-dd HH:mm:ss") ➡️ @Clock.ConvertToUserTime(context.EndTime).ToString("yyyy-MM-dd HH:mm:ss") + + + + + @Clock.ConvertToUserTime(context.ActualStartTime).ToString("yyyy-MM-dd HH:mm:ss") + + + + + @(context.CanceledTime.HasValue ? Clock.ConvertToUserTime(context.CanceledTime.Value).ToString("yyyy-MM-dd HH:mm:ss") : "N/A") + + + + + @(Clock.ConvertToUserTime(context.ReminderTime).ToString("yyyy-MM-dd HH:mm:ss") ) + + + + + @(context.FollowUpTime.HasValue ? Clock.ConvertToUserTime(context.FollowUpTime.Value).ToString("yyyy-MM-dd HH:mm:ss") : "N/A") + + + + + + + +
+ + + +
+ + @L["NewMeeting"] + + + + + + + @L["Subject"] + + + + + + + + + @L["StartTime"] / @L["EndTime"] + + + + @L["ActualStartTime"] + + + + @L["CanceledTime"] + + + + @L["ReminderTime"] + + + + @L["FollowUpTime"] + + + + + @L["Description"] + + + + + + + + + + + + + +
+
+
+ + + +
+ + @EditingEntity.Subject + + + + + + + @L["Subject"] + + + + + + + + + @L["StartTime"] / @L["EndTime"] + + + + @L["ActualStartTime"] + + + + @L["CanceledTime"] + + + + @L["ReminderTime"] + + + + @L["FollowUpTime"] + + + + + @L["Description"] + + + + + + + + + + + + + +
+
+
+ + +@code { + IReadOnlyList SelectedDates; + + public Meeting() + { + CreatePolicyName = TimeZoneAppPermissions.Meetings.Create; + UpdatePolicyName = TimeZoneAppPermissions.Meetings.Edit; + DeletePolicyName = TimeZoneAppPermissions.Meetings.Delete; + } + + protected override async Task OpenCreateModalAsync() + { + await base.OpenCreateModalAsync(); + + var now = DateTime.Now; + SelectedDates = new List { now.Date.AddHours(10),now.Date.AddDays(7).AddHours(10) }; + NewEntity.ActualStartTime = now.Date.AddHours(11); + NewEntity.CanceledTime = now.Date.AddHours(12); + NewEntity.ReminderTime = now.Date.AddHours(13); + NewEntity.FollowUpTime = now.Date.AddHours(14); + } + + protected override Task OnCreatingEntityAsync() + { + if (SelectedDates.Count == 2 && SelectedDates[0].HasValue && SelectedDates[1].HasValue) + { + NewEntity.StartTime = Clock.ConvertToUtc(SelectedDates[0]!.Value); + NewEntity.EndTime = Clock.ConvertToUtc(SelectedDates[1]!.Value); + } + + NewEntity.ActualStartTime = Clock.ConvertToUtc(NewEntity.ActualStartTime); + NewEntity.CanceledTime = NewEntity.CanceledTime.HasValue ? Clock.ConvertToUtc(NewEntity.CanceledTime.Value) : null; + + NewEntity.ReminderTime = Clock.ConvertToUtc(NewEntity.ReminderTime.DateTime); + NewEntity.FollowUpTime = NewEntity.FollowUpTime.HasValue ? Clock.ConvertToUtc(NewEntity.FollowUpTime.Value.DateTime) : null; + + return Task.CompletedTask; + } + + protected override async Task OpenEditModalAsync(MeetingDto entity) + { + await base.OpenEditModalAsync(entity); + + SelectedDates = new List { Clock.ConvertToUserTime(EditingEntity.StartTime), Clock.ConvertToUserTime(EditingEntity.EndTime) }; + EditingEntity.ActualStartTime = Clock.ConvertToUserTime(EditingEntity.ActualStartTime); + EditingEntity.CanceledTime = EditingEntity.CanceledTime.HasValue ? Clock.ConvertToUserTime(EditingEntity.CanceledTime.Value) : null; + EditingEntity.ReminderTime = Clock.ConvertToUserTime(EditingEntity.ReminderTime); + EditingEntity.FollowUpTime = EditingEntity.FollowUpTime.HasValue ? Clock.ConvertToUserTime(EditingEntity.FollowUpTime.Value) : null; + } + + protected override Task OnUpdatingEntityAsync() + { + if (SelectedDates.Count == 2 && SelectedDates[0].HasValue && SelectedDates[1].HasValue) + { + EditingEntity.StartTime = Clock.ConvertToUtc(SelectedDates[0]!.Value); + EditingEntity.EndTime = Clock.ConvertToUtc(SelectedDates[1]!.Value); + } + + EditingEntity.ActualStartTime = Clock.ConvertToUtc(EditingEntity.ActualStartTime); + EditingEntity.CanceledTime = EditingEntity.CanceledTime.HasValue ? Clock.ConvertToUtc(EditingEntity.CanceledTime.Value) : null; + + return Task.CompletedTask; + } +} +``` + +![](blazor-list.png) + +![](blazor-create.png) + +![](blazor-edit.png) + +## Timezone Settings Change + +If the timezone settings change, then all times will be converted to the new timezone. For example, if the current timezone changes from `Europe/Istanbul` to `Europe/Berlin`, then all times will be converted to the `Europe/Berlin` timezone. + +![](berlin.png) + +`Europe/Istanbul`: + +![](auth-list-utc3.png) + +![](mvc-list-utc3.png) + +`Europe/Berlin`: + +![](auth-list-utc1.png) + +![](mvc-list-utc1.png) + +## Browser Timezone Detection + +When no timezone setting is configured, ABP's MVC, Blazor, and Angular applications will automatically detect the browser's timezone during initialization. The detected timezone is then stored in either the request's Cookie or Header. + +This functionality is implemented by the `UseAbpTimeZone` middleware, which follows a specific order to determine the appropriate timezone: + +1. First, it attempts to retrieve the timezone from the application/tenant/user settings +2. If no setting is found, it tries to get the timezone from the request information, including Cookie, Header, QueryString, and Form +3. Finally, if no timezone information is found, it falls back to using the server's timezone as the default + +> The timezone information is stored using the key `__timezone` + +## TimeZoneApp Source Code + +You can download and view the [TimeZoneApp source code](https://github.com/maliming/TimeZone) for detailed implementation. + +## Summary + +Through this article, we learned how to handle timezone in different types of UIs. I hope this article is helpful to you. If you have any questions, please contact me at any time. diff --git a/docs/en/framework/infrastructure/timing.md b/docs/en/framework/infrastructure/timing.md index be5569f863..9f104b6336 100644 --- a/docs/en/framework/infrastructure/timing.md +++ b/docs/en/framework/infrastructure/timing.md @@ -88,6 +88,61 @@ var normalizedDateTime = Clock.Normalize(dateTime) `DisableDateTimeNormalization` attribute can be used to disable the normalization operation for desired classes or properties. +### DateTime Converter Between UTC and User's Time Zone + +#### Convert given UTC to user's time zone. + +`DateTime ConvertToUserTime(DateTime utcDateTime)` and `DateTimeOffset ConvertToUserTime(DateTimeOffset dateTimeOffset)` methods convert given UTC `DateTime` or `DateTimeOffset` to the user's time zone. + +> If `SupportsMultipleTimezone` is `false` or `dateTime.Kind` is not `Utc` or these is no timezone setting, it returns the given `DateTime` or `DateTimeOffset` without any changes. + +**Example:** + +If user's `TimeZone Setting` is `Europe/Istanbul` + +````csharp +// 2025-03-01T05:30:00Z +var utcTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc); + +var userTime = Clock.ConvertToUserTime(utcTime); + +// Europe/Istanbul has 3 hours difference with UTC. So, the result will be 3 hours later. +userTime.Kind.ShouldBe(DateTimeKind.Unspecified); +userTime.ToString("O").ShouldBe("2025-03-01T08:30:00"); +```` + +````csharp +// 2025-03-01T05:30:00Z +var utcTime = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc), TimeSpan.Zero); + +var userTime = Clock.ConvertToUserTime(utcTime); + +// Europe/Istanbul has 3 hours difference with UTC. So, the result will be 3 hours later. +userTime.Offset.ShouldBe(TimeSpan.FromHours(3)); +userTime.ToString("O").ShouldBe("2025-03-01T08:30:00.0000000+03:00"); +```` + +#### Converts given user's DateTime to UTC + +`DateTime ConvertToUtc(DateTime dateTime)` method convert given user's `DateTime` to UTC. + +> If `SupportsMultipleTimezone` is `false` or `dateTime.Kind` is `Utc` or these is no timezone setting, it returns the given `DateTime` without any changes. + +**Example:** + +If user's `TimeZone Setting` is `Europe/Istanbul` + +````csharp +// 2025-03-01T05:30:00 +var userTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified); //Same as Local + +var utcTime = Clock.ConvertToUtc(userTime); + +// Europe/Istanbul has 3 hours difference with UTC. So, the result will be 3 hours earlier. +utcTime.Kind.ShouldBe(DateTimeKind.Utc); +utcTime.ToString("O").ShouldBe("2025-03-01T02:30:00.0000000Z"); +```` + ### Other IClock Properties In addition to the `Now`, `IClock` service has the following properties: @@ -101,10 +156,24 @@ This section covers the ABP infrastructure related to managing time zones. ### TimeZone Setting -ABP defines **a setting**, named `Abp.Timing.TimeZone`, that can be used to set and get the time zone for a user, [tenant](../architecture/multi-tenancy) or globally for the application. The default value is `UTC`. +ABP defines **a setting**, named `Abp.Timing.TimeZone`, that can be used to set and get the time zone for a user, [tenant](../architecture/multi-tenancy) or globally for the application. The default value is empty, which means the application will use the server's time zone. + +You can change your host/tenant global time zone in the [Settings Management UI](../../modules/setting-management#setting-management-ui) + +The [Account Pro Module](../../modules/account-pro#Time-Zone-Setting) supports user to set their own time zone in the account settings page. See the [setting documentation](../infrastructure/settings.md) to learn more about the setting system. +### UseAbpTimeZone Middleware + +The `app.UseAbpTimeZone()` middleware is used to set the time zone for the current request. + + * It will get timezone from settings, the order is `User` -> `Tenant` -> `Application/Global`. + * If current request is anonymous, it will get timezone from the request header/cookie/form/query string. the key is `__timezone`. + +> If you want to get current timezone, you can inject `ICurrentTimezoneProvider` service. +> Please add this middleware after authentication. + ### ITimezoneProvider `ITimezoneProvider` is a service to simply convert [Windows Time Zone Id](https://support.microsoft.com/en-us/help/973627/microsoft-time-zone-index-values) values to [Iana Time Zone Name](https://www.iana.org/time-zones) values and vice verse. It also provides methods to get the list of these time zones and get a `TimeZoneInfo` with a given name. diff --git a/docs/en/images/account-pro-time-zone-setting.png b/docs/en/images/account-pro-time-zone-setting.png new file mode 100644 index 0000000000..687ad7db70 Binary files /dev/null and b/docs/en/images/account-pro-time-zone-setting.png differ diff --git a/docs/en/images/setting-management-email-ui.png b/docs/en/images/setting-management-email-ui.png index ab26a1d180..f02e8cd1c4 100644 Binary files a/docs/en/images/setting-management-email-ui.png and b/docs/en/images/setting-management-email-ui.png differ diff --git a/docs/en/images/setting-management-feature-management-ui.png b/docs/en/images/setting-management-feature-management-ui.png new file mode 100644 index 0000000000..b534fe830b Binary files /dev/null and b/docs/en/images/setting-management-feature-management-ui.png differ diff --git a/docs/en/images/setting-management-time-zone-ui.png b/docs/en/images/setting-management-time-zone-ui.png new file mode 100644 index 0000000000..fe65256ab5 Binary files /dev/null and b/docs/en/images/setting-management-time-zone-ui.png differ diff --git a/docs/en/modules/account-pro.md b/docs/en/modules/account-pro.md index 4ccc8b316a..c53a6f24ec 100644 --- a/docs/en/modules/account-pro.md +++ b/docs/en/modules/account-pro.md @@ -273,6 +273,12 @@ Users who register via both local registration and external/social login using t ![require-local-password-on-social-account-linking](../images/require-local-password-on-social-account-linking.png) +### Time Zone Setting + +Users can to set their own time zone in the account settings page if application is [supports multiple timezones](../framework/infrastructure/timing.md#clock-options). + +![account-pro-time-zone-setting](../images/account-pro-time-zone-setting.png) + ## Internals ### Settings diff --git a/docs/en/modules/setting-management.md b/docs/en/modules/setting-management.md index 32dd52f4b6..842233e8b4 100644 --- a/docs/en/modules/setting-management.md +++ b/docs/en/modules/setting-management.md @@ -118,12 +118,16 @@ The order of the providers are important. Providers are executed in the reverse ## Setting Management UI -Setting Mangement module provided the email setting UI by default. +Setting Mangement module provided the Email setting, Feature management and Timezone setting UI by default. ![EmailSettingUi](../images/setting-management-email-ui.png) > You can click the Send test email button to send a test email to check your email settings. +![FeatureManagementUi](../images/setting-management-feature-management-ui.png) + +![TimeZoneSettingUi](../images/setting-management-time-zone-ui.png) + Setting it is extensible; You can add your tabs to this page for your application settings. ### MVC UI diff --git a/framework/Volo.Abp.sln b/framework/Volo.Abp.sln index db7bc55ff2..78f7ae0011 100644 --- a/framework/Volo.Abp.sln +++ b/framework/Volo.Abp.sln @@ -489,6 +489,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.BlobStoring.Bunny" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.BlobStoring.Bunny.Tests", "test\Volo.Abp.BlobStoring.Bunny.Tests\Volo.Abp.BlobStoring.Bunny.Tests.csproj", "{BC4BB2D6-DFD8-4190-AAC3-32C0A7A8E915}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Volo.Abp.Timing.Tests", "test\Volo.Abp.Timing.Tests\Volo.Abp.Timing.Tests.csproj", "{58FCF22D-E8DB-4EB8-B586-9BB6E9899D64}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1459,6 +1461,10 @@ Global {BC4BB2D6-DFD8-4190-AAC3-32C0A7A8E915}.Debug|Any CPU.Build.0 = Debug|Any CPU {BC4BB2D6-DFD8-4190-AAC3-32C0A7A8E915}.Release|Any CPU.ActiveCfg = Release|Any CPU {BC4BB2D6-DFD8-4190-AAC3-32C0A7A8E915}.Release|Any CPU.Build.0 = Release|Any CPU + {58FCF22D-E8DB-4EB8-B586-9BB6E9899D64}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {58FCF22D-E8DB-4EB8-B586-9BB6E9899D64}.Debug|Any CPU.Build.0 = Debug|Any CPU + {58FCF22D-E8DB-4EB8-B586-9BB6E9899D64}.Release|Any CPU.ActiveCfg = Release|Any CPU + {58FCF22D-E8DB-4EB8-B586-9BB6E9899D64}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1705,6 +1711,7 @@ Global {70720321-DED4-464F-B913-BDA5BBDD7982} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} {1BBCBA72-CDB6-4882-96EE-D4CD149433A2} = {5DF0E140-0513-4D0D-BE2E-3D4D85CD70E6} {BC4BB2D6-DFD8-4190-AAC3-32C0A7A8E915} = {447C8A77-E5F0-4538-8687-7383196D04EA} + {58FCF22D-E8DB-4EB8-B586-9BB6E9899D64} = {447C8A77-E5F0-4538-8687-7383196D04EA} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {BB97ECF4-9A84-433F-A80B-2A3285BDD1D5} diff --git a/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/AbpMauiBlazorClientHttpMessageHandler.cs b/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/AbpMauiBlazorClientHttpMessageHandler.cs index 9fb31979ac..562f35e5a8 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/AbpMauiBlazorClientHttpMessageHandler.cs +++ b/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/AbpMauiBlazorClientHttpMessageHandler.cs @@ -6,6 +6,7 @@ using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.AspNetCore.Components.Progression; using Volo.Abp.DependencyInjection; +using Volo.Abp.Timing; namespace Volo.Abp.AspNetCore.Components.MauiBlazor; @@ -13,12 +14,15 @@ public class AbpMauiBlazorClientHttpMessageHandler : DelegatingHandler, ITransie { private readonly IUiPageProgressService _uiPageProgressService; private readonly IMauiBlazorSelectedLanguageProvider _mauiBlazorSelectedLanguageProvider; + private readonly ICurrentTimezoneProvider _currentTimezoneProvider; public AbpMauiBlazorClientHttpMessageHandler( IClientScopeServiceProviderAccessor clientScopeServiceProviderAccessor, - IMauiBlazorSelectedLanguageProvider mauiBlazorSelectedLanguageProvider) + IMauiBlazorSelectedLanguageProvider mauiBlazorSelectedLanguageProvider, + ICurrentTimezoneProvider currentTimezoneProvider) { _mauiBlazorSelectedLanguageProvider = mauiBlazorSelectedLanguageProvider; + _currentTimezoneProvider = currentTimezoneProvider; _uiPageProgressService = clientScopeServiceProviderAccessor.ServiceProvider.GetRequiredService(); } @@ -32,6 +36,7 @@ public class AbpMauiBlazorClientHttpMessageHandler : DelegatingHandler, ITransie }); await SetLanguageAsync(request); + await SetTimeZoneAsync(request); return await base.SendAsync(request, cancellationToken); } @@ -51,4 +56,15 @@ public class AbpMauiBlazorClientHttpMessageHandler : DelegatingHandler, ITransie request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(selectedLanguage!)); } } -} \ No newline at end of file + + private Task SetTimeZoneAsync(HttpRequestMessage request) + { + if (!_currentTimezoneProvider.TimeZone.IsNullOrWhiteSpace()) + { + request.Headers.Remove(TimeZoneConsts.DefaultTimeZoneKey); + request.Headers.Add(TimeZoneConsts.DefaultTimeZoneKey, _currentTimezoneProvider.TimeZone); + } + + return Task.CompletedTask; + } +} diff --git a/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/MauiBlazorCachedApplicationConfigurationClient.cs b/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/MauiBlazorCachedApplicationConfigurationClient.cs index c2fd8e21aa..a48901f6dd 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/MauiBlazorCachedApplicationConfigurationClient.cs +++ b/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/MauiBlazorCachedApplicationConfigurationClient.cs @@ -1,10 +1,13 @@ -using System.Threading.Tasks; +using System; +using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.JSInterop; using Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations; using Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations.ClientProxies; using Volo.Abp.AspNetCore.Mvc.Client; using Volo.Abp.DependencyInjection; using Volo.Abp.MultiTenancy; +using Volo.Abp.Timing; namespace Volo.Abp.AspNetCore.Components.MauiBlazor { @@ -18,17 +21,29 @@ namespace Volo.Abp.AspNetCore.Components.MauiBlazor protected ICurrentTenantAccessor CurrentTenantAccessor { get; } + protected ICurrentTimezoneProvider CurrentTimezoneProvider { get; } + + protected IJSRuntime JSRuntime { get; } + + protected IClock Clock { get; } + public MauiBlazorCachedApplicationConfigurationClient( AbpApplicationConfigurationClientProxy applicationConfigurationClientProxy, ApplicationConfigurationCache cache, ICurrentTenantAccessor currentTenantAccessor, + ICurrentTimezoneProvider currentTimezoneProvider, AuthenticationStateProvider authenticationStateProvider, - AbpApplicationLocalizationClientProxy applicationLocalizationClientProxy) + AbpApplicationLocalizationClientProxy applicationLocalizationClientProxy, + IJSRuntime jsRuntime, + IClock clock) { ApplicationConfigurationClientProxy = applicationConfigurationClientProxy; Cache = cache; CurrentTenantAccessor = currentTenantAccessor; + CurrentTimezoneProvider = currentTimezoneProvider; ApplicationLocalizationClientProxy = applicationLocalizationClientProxy; + JSRuntime = jsRuntime; + Clock = clock; authenticationStateProvider.AuthenticationStateChanged += async _ => { await InitializeAsync(); }; } @@ -57,6 +72,15 @@ namespace Volo.Abp.AspNetCore.Components.MauiBlazor CurrentTenantAccessor.Current = new BasicTenantInfo( configurationDto.CurrentTenant.Id, configurationDto.CurrentTenant.Name); + + if (Clock.SupportsMultipleTimezone) + { + CurrentTimezoneProvider.TimeZone = !configurationDto.Timing.TimeZone.Iana.TimeZoneName.IsNullOrWhiteSpace() + ? configurationDto.Timing.TimeZone.Iana.TimeZoneName + : await JSRuntime.InvokeAsync("abp.clock.getBrowserTimeZone"); + + await JSRuntime.InvokeAsync("abp.clock.setBrowserTimeZoneToCookie"); + } } public virtual Task GetAsync() @@ -81,4 +105,4 @@ namespace Volo.Abp.AspNetCore.Components.MauiBlazor return configuration; } } -} \ No newline at end of file +} diff --git a/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/MauiBlazorCurrentTimezoneProvider.cs b/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/MauiBlazorCurrentTimezoneProvider.cs new file mode 100644 index 0000000000..2a1a37da07 --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.Components.MauiBlazor/Volo/Abp/AspNetCore/Components/MauiBlazor/MauiBlazorCurrentTimezoneProvider.cs @@ -0,0 +1,10 @@ +using Volo.Abp.DependencyInjection; +using Volo.Abp.Timing; + +namespace Volo.Abp.AspNetCore.Components.MauiBlazor; + +[Dependency(ReplaceServices = true)] +public class MauiBlazorCurrentTimezoneProvider : ICurrentTimezoneProvider, ISingletonDependency +{ + public string? TimeZone { get; set; } +} diff --git a/framework/src/Volo.Abp.AspNetCore.Components.Web/Volo/Abp/AspNetCore/Components/Web/AbpBlazorClientHttpMessageHandler.cs b/framework/src/Volo.Abp.AspNetCore.Components.Web/Volo/Abp/AspNetCore/Components/Web/AbpBlazorClientHttpMessageHandler.cs index c92c121628..5fa70baabe 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.Web/Volo/Abp/AspNetCore/Components/Web/AbpBlazorClientHttpMessageHandler.cs +++ b/framework/src/Volo.Abp.AspNetCore.Components.Web/Volo/Abp/AspNetCore/Components/Web/AbpBlazorClientHttpMessageHandler.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.JSInterop; using Volo.Abp.AspNetCore.Components.Progression; using Volo.Abp.DependencyInjection; +using Volo.Abp.Timing; namespace Volo.Abp.AspNetCore.Components.Web; @@ -21,6 +22,8 @@ public class AbpBlazorClientHttpMessageHandler : DelegatingHandler, ITransientDe private readonly IUiPageProgressService _uiPageProgressService; + private readonly ICurrentTimezoneProvider _currentTimezoneProvider; + private const string AntiForgeryCookieName = "XSRF-TOKEN"; private const string AntiForgeryHeaderName = "RequestVerificationToken"; @@ -29,11 +32,13 @@ public class AbpBlazorClientHttpMessageHandler : DelegatingHandler, ITransientDe IJSRuntime jsRuntime, ICookieService cookieService, NavigationManager navigationManager, - IClientScopeServiceProviderAccessor clientScopeServiceProviderAccessor) + IClientScopeServiceProviderAccessor clientScopeServiceProviderAccessor, + ICurrentTimezoneProvider currentTimezoneProvider) { _jsRuntime = jsRuntime; _cookieService = cookieService; _navigationManager = navigationManager; + _currentTimezoneProvider = currentTimezoneProvider; _uiPageProgressService = clientScopeServiceProviderAccessor.ServiceProvider.GetRequiredService(); } @@ -48,6 +53,7 @@ public class AbpBlazorClientHttpMessageHandler : DelegatingHandler, ITransientDe await SetLanguageAsync(request, cancellationToken); await SetAntiForgeryTokenAsync(request); + await SetTimeZoneAsync(request); return await base.SendAsync(request, cancellationToken); } @@ -94,4 +100,15 @@ public class AbpBlazorClientHttpMessageHandler : DelegatingHandler, ITransientDe request.Headers.Add(AntiForgeryHeaderName, token); } } + + private Task SetTimeZoneAsync(HttpRequestMessage request) + { + if (!_currentTimezoneProvider.TimeZone.IsNullOrWhiteSpace()) + { + request.Headers.Remove(TimeZoneConsts.DefaultTimeZoneKey); + request.Headers.Add(TimeZoneConsts.DefaultTimeZoneKey, _currentTimezoneProvider.TimeZone); + } + + return Task.CompletedTask; + } } diff --git a/framework/src/Volo.Abp.AspNetCore.Components.Web/wwwroot/libs/abp/js/abp.js b/framework/src/Volo.Abp.AspNetCore.Components.Web/wwwroot/libs/abp/js/abp.js index 51ff0151b6..30f1915005 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.Web/wwwroot/libs/abp/js/abp.js +++ b/framework/src/Volo.Abp.AspNetCore.Components.Web/wwwroot/libs/abp/js/abp.js @@ -245,4 +245,14 @@ var abp = abp || {}; } } } + + abp.clock = abp.clock || {}; + + abp.clock.setBrowserTimeZoneToCookie = function () { + abp.utils.setCookieValue('__timezone', Intl.DateTimeFormat().resolvedOptions().timeZone, new Date(new Date().setFullYear(new Date().getFullYear() + 1)), '/'); + } + + abp.clock.getBrowserTimeZone = function () { + return Intl.DateTimeFormat().resolvedOptions().timeZone + } })(); diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Volo/Abp/AspNetCore/Components/WebAssembly/WebAssemblyCachedApplicationConfigurationClient.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Volo/Abp/AspNetCore/Components/WebAssembly/WebAssemblyCachedApplicationConfigurationClient.cs index bebb2a78e1..aa80a5c3b0 100644 --- a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Volo/Abp/AspNetCore/Components/WebAssembly/WebAssemblyCachedApplicationConfigurationClient.cs +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Volo/Abp/AspNetCore/Components/WebAssembly/WebAssemblyCachedApplicationConfigurationClient.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System; +using System.Threading.Tasks; using Microsoft.JSInterop; using Volo.Abp.AspNetCore.Components.Web.Security; using Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations; @@ -6,6 +7,7 @@ using Volo.Abp.AspNetCore.Mvc.ApplicationConfigurations.ClientProxies; using Volo.Abp.AspNetCore.Mvc.Client; using Volo.Abp.DependencyInjection; using Volo.Abp.MultiTenancy; +using Volo.Abp.Timing; namespace Volo.Abp.AspNetCore.Components.WebAssembly; @@ -19,24 +21,32 @@ public class WebAssemblyCachedApplicationConfigurationClient : ICachedApplicatio protected ICurrentTenantAccessor CurrentTenantAccessor { get; } + protected ICurrentTimezoneProvider CurrentTimezoneProvider { get; } + protected ApplicationConfigurationChangedService ApplicationConfigurationChangedService { get; } protected IJSRuntime JSRuntime { get; } + protected IClock Clock { get; } + public WebAssemblyCachedApplicationConfigurationClient( AbpApplicationConfigurationClientProxy applicationConfigurationClientProxy, ApplicationConfigurationCache cache, ICurrentTenantAccessor currentTenantAccessor, + ICurrentTimezoneProvider currentTimezoneProvider, AbpApplicationLocalizationClientProxy applicationLocalizationClientProxy, ApplicationConfigurationChangedService applicationConfigurationChangedService, - IJSRuntime jsRuntime) + IJSRuntime jsRuntime, + IClock clock) { ApplicationConfigurationClientProxy = applicationConfigurationClientProxy; Cache = cache; CurrentTenantAccessor = currentTenantAccessor; + CurrentTimezoneProvider = currentTimezoneProvider; ApplicationLocalizationClientProxy = applicationLocalizationClientProxy; ApplicationConfigurationChangedService = applicationConfigurationChangedService; JSRuntime = jsRuntime; + Clock = clock; } public virtual async Task InitializeAsync() @@ -69,6 +79,15 @@ public class WebAssemblyCachedApplicationConfigurationClient : ICachedApplicatio configurationDto.CurrentTenant.Id, configurationDto.CurrentTenant.Name ); + + if (Clock.SupportsMultipleTimezone) + { + CurrentTimezoneProvider.TimeZone = !configurationDto.Timing.TimeZone.Iana.TimeZoneName.IsNullOrWhiteSpace() + ? configurationDto.Timing.TimeZone.Iana.TimeZoneName + : await JSRuntime.InvokeAsync("abp.clock.getBrowserTimeZone"); + + await JSRuntime.InvokeAsync("abp.clock.setBrowserTimeZoneToCookie"); + } } public virtual Task GetAsync() diff --git a/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Volo/Abp/AspNetCore/Components/WebAssembly/WebAssemblyCurrentTimezoneProvider.cs b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Volo/Abp/AspNetCore/Components/WebAssembly/WebAssemblyCurrentTimezoneProvider.cs new file mode 100644 index 0000000000..c387ec30ea --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore.Components.WebAssembly/Volo/Abp/AspNetCore/Components/WebAssembly/WebAssemblyCurrentTimezoneProvider.cs @@ -0,0 +1,10 @@ +using Volo.Abp.DependencyInjection; +using Volo.Abp.Timing; + +namespace Volo.Abp.AspNetCore.Components.WebAssembly; + +[Dependency(ReplaceServices = true)] +public class WebAssemblyCurrentTimezoneProvider : ICurrentTimezoneProvider, ISingletonDependency +{ + public string? TimeZone { get; set; } +} diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc.NewtonsoftJson/Volo/Abp/AspNetCore/Mvc/NewtonsoftJson/AbpAspNetCoreMvcNewtonsoftModule.cs b/framework/src/Volo.Abp.AspNetCore.Mvc.NewtonsoftJson/Volo/Abp/AspNetCore/Mvc/NewtonsoftJson/AbpAspNetCoreMvcNewtonsoftModule.cs index d213c9f451..95e07a06e0 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc.NewtonsoftJson/Volo/Abp/AspNetCore/Mvc/NewtonsoftJson/AbpAspNetCoreMvcNewtonsoftModule.cs +++ b/framework/src/Volo.Abp.AspNetCore.Mvc.NewtonsoftJson/Volo/Abp/AspNetCore/Mvc/NewtonsoftJson/AbpAspNetCoreMvcNewtonsoftModule.cs @@ -16,7 +16,9 @@ public class AbpAspNetCoreMvcNewtonsoftModule : AbpModule context.Services.AddOptions() .Configure((options, rootServiceProvider) => { - options.SerializerSettings.ContractResolver = new AbpCamelCasePropertyNamesContractResolver(rootServiceProvider.GetRequiredService()); + options.SerializerSettings.ContractResolver = + new AbpCamelCasePropertyNamesContractResolver(rootServiceProvider + .GetRequiredService()); }); } } diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Form/DatePicker/AbpDatePickerBaseTagHelperService.cs b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Form/DatePicker/AbpDatePickerBaseTagHelperService.cs index bd3a4abe48..5088c08293 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Form/DatePicker/AbpDatePickerBaseTagHelperService.cs +++ b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Form/DatePicker/AbpDatePickerBaseTagHelperService.cs @@ -16,63 +16,28 @@ using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.Microsoft.AspNetCore.Razor.TagHelpers using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Button; using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Extensions; using Volo.Abp.Json; +using Volo.Abp.Timing; namespace Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Form.DatePicker; public abstract class AbpDatePickerBaseTagHelperService : AbpTagHelperService where TTagHelper : AbpDatePickerBaseTagHelper { - protected readonly Dictionary> SupportedInputTypes = new() - { - { - typeof(string), o => - { - if(o is string s && DateTime.TryParse(s, out var dt)) - { - return dt.ToString("O"); - } - - return string.Empty; - } - }, - { - typeof(DateTime), o => - { - if(o is DateTime dt && dt != default) - { - return dt.ToString("O"); - } - - return string.Empty; - } - }, - {typeof(DateTime?), o => ((DateTime?) o)?.ToString("O")!}, - { - typeof(DateTimeOffset), o => - { - if(o is DateTimeOffset dto && dto != default) - { - return dto.ToString("O"); - } - - return string.Empty; - } - }, - {typeof(DateTimeOffset?), o => ((DateTimeOffset?) o)?.ToString("O")!} - }; + protected readonly Dictionary> SupportedInputTypes; protected readonly IJsonSerializer JsonSerializer; protected readonly IHtmlGenerator Generator; protected readonly HtmlEncoder Encoder; protected readonly IServiceProvider ServiceProvider; protected readonly IAbpTagHelperLocalizer TagHelperLocalizer; + protected readonly IClock Clock; protected virtual string TagName { get; set; } = "abp-date-picker"; protected IStringLocalizer L { get; } protected abstract TagHelperOutput TagHelperOutput { get; set; } protected AbpDatePickerBaseTagHelperService(IJsonSerializer jsonSerializer, IHtmlGenerator generator, HtmlEncoder encoder, IServiceProvider serviceProvider, IStringLocalizer l, - IAbpTagHelperLocalizer tagHelperLocalizer) + IAbpTagHelperLocalizer tagHelperLocalizer, IClock clock) { JsonSerializer = jsonSerializer; Generator = generator; @@ -80,6 +45,65 @@ public abstract class AbpDatePickerBaseTagHelperService : AbpTagHelp ServiceProvider = serviceProvider; L = l; TagHelperLocalizer = tagHelperLocalizer; + Clock = clock; + + SupportedInputTypes = new Dictionary> + { + { + typeof(string), x => + { + if(x is string s && DateTime.TryParse(s, out var dt)) + { + return Clock.ConvertToUserTime(dt).ToString("O"); + } + + return string.Empty; + } + }, + { + typeof(DateTime), x => + { + if(x is DateTime dt && dt != default) + { + return Clock.ConvertToUserTime(dt).ToString("O"); + } + + return string.Empty; + } + }, + { + typeof(DateTime?), x => + { + if(x is DateTime dt && dt != default) + { + return Clock.ConvertToUserTime(dt).ToString("O"); + } + return string.Empty; + } + }, + { + typeof(DateTimeOffset), x => + { + if(x is DateTimeOffset dto && dto != default) + { + return Clock.ConvertToUserTime(dto).DateTime.ToString("O"); + } + + return string.Empty; + } + }, + { + typeof(DateTimeOffset?), x => + { + if(x is DateTimeOffset dto && dto != default) + { + return Clock.ConvertToUserTime(dto).DateTime.ToString("O"); + } + + return string.Empty; + } + } + }; } protected virtual T? GetAttribute() where T : Attribute @@ -233,6 +257,7 @@ public abstract class AbpDatePickerBaseTagHelperService : AbpTagHelp } protected abstract int GetOrder(); + protected abstract void AddBaseTagAttributes(TagHelperAttributeList attributes); protected virtual string GetExtraInputHtml(TagHelperContext context, TagHelperOutput output) @@ -375,7 +400,7 @@ public abstract class AbpDatePickerBaseTagHelperService : AbpTagHelp { attrList.Add("data-visible-date-format", options.VisibleDateFormat); } - + if(!options.InputDateFormat.IsNullOrEmpty()) { attrList.Add("data-input-date-format", options.InputDateFormat); @@ -754,7 +779,7 @@ public abstract class AbpDatePickerBaseTagHelperService : AbpTagHelp { return Task.FromResult(string.Empty); } - + return GetValidationAsHtmlByInputAsync(context, output, @for); } @@ -766,7 +791,7 @@ public abstract class AbpDatePickerBaseTagHelperService : AbpTagHelp new ValidationMessageTagHelper(Generator) { For = @for, ViewContext = TagHelper.ViewContext }; var attributeList = new TagHelperAttributeList { { "class", "text-danger" } }; - + if(!output.Attributes.TryGetAttribute("name", out var nameAttribute) || nameAttribute == null || nameAttribute.Value == null) { if (nameAttribute != null) @@ -776,7 +801,7 @@ public abstract class AbpDatePickerBaseTagHelperService : AbpTagHelp nameAttribute = new TagHelperAttribute("name", "date_" + Guid.NewGuid().ToString("N")); output.Attributes.Add(nameAttribute); } - + attributeList.Add("data-valmsg-for", nameAttribute.Value); return await validationMessageTagHelper.RenderAsync(attributeList, context, Encoder, "span", diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Form/DatePicker/AbpDatePickerTagHelperService.cs b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Form/DatePicker/AbpDatePickerTagHelperService.cs index 3fc2861b59..5370a9a7de 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Form/DatePicker/AbpDatePickerTagHelperService.cs +++ b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Bootstrap/TagHelpers/Form/DatePicker/AbpDatePickerTagHelperService.cs @@ -8,14 +8,22 @@ using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.Localization; using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Extensions; using Volo.Abp.Json; +using Volo.Abp.Timing; namespace Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Form.DatePicker; public class AbpDatePickerTagHelperService : AbpDatePickerBaseTagHelperService { - public AbpDatePickerTagHelperService(IJsonSerializer jsonSerializer, IHtmlGenerator generator, HtmlEncoder encoder, IServiceProvider serviceProvider, IStringLocalizer l, IAbpTagHelperLocalizer tagHelperLocalizer) : base(jsonSerializer, generator, encoder, serviceProvider, l, tagHelperLocalizer) + public AbpDatePickerTagHelperService( + IJsonSerializer jsonSerializer, + IHtmlGenerator generator, + HtmlEncoder encoder, + IServiceProvider serviceProvider, + IStringLocalizer l, + IAbpTagHelperLocalizer tagHelperLocalizer, + IClock clock) + : base(jsonSerializer, generator, encoder, serviceProvider, l, tagHelperLocalizer, clock) { - } protected override TagHelperOutput TagHelperOutput { get; set; } = default!; @@ -42,10 +50,28 @@ public class AbpDatePickerTagHelperService : AbpDatePickerBaseTagHelperService { - public AbpDateRangePickerTagHelperService(IJsonSerializer jsonSerializer, IHtmlGenerator generator, - HtmlEncoder encoder, IServiceProvider serviceProvider, IStringLocalizer l, - IAbpTagHelperLocalizer tagHelperLocalizer) : - base(jsonSerializer, generator, encoder, serviceProvider, l, - tagHelperLocalizer) + public AbpDateRangePickerTagHelperService( + IJsonSerializer jsonSerializer, IHtmlGenerator generator, + HtmlEncoder encoder, + IServiceProvider serviceProvider, + IStringLocalizer l, + IAbpTagHelperLocalizer tagHelperLocalizer, + IClock clock) : + base(jsonSerializer, generator, encoder, serviceProvider, l, tagHelperLocalizer, clock) { } @@ -34,7 +38,7 @@ public class AbpDateRangePickerTagHelperService : AbpDatePickerBaseTagHelperServ { if (TagHelper.AspForStart != null) { - var startDateAttributes = new TagHelperAttributeList { { "data-start-date", "true" }, { "type", "hidden" } }; + var startDateAttributes = new TagHelperAttributeList { { "data-hidden-datepicker", "true" }, { "data-start-date", "true" }, { "type", "hidden" } }; StartDateTagHelper = new InputTagHelper(Generator) { ViewContext = TagHelper.ViewContext, @@ -42,12 +46,29 @@ public class AbpDateRangePickerTagHelperService : AbpDatePickerBaseTagHelperServ InputTypeName = "hidden" }; + if (Clock.SupportsMultipleTimezone) + { + if (TagHelper.AspForStart.Model is DateTime dateTime) + { + StartDateTagHelper.Format = "{0:O}"; + StartDateTagHelper.Value = Clock.ConvertToUserTime(dateTime).ToString("O"); + startDateAttributes.Add("value", StartDateTagHelper.Value); + } + + if (TagHelper.AspForStart.Model is DateTimeOffset dateTimeOffset) + { + StartDateTagHelper.Format = "{0:O}"; + StartDateTagHelper.Value = Clock.ConvertToUserTime(dateTimeOffset).UtcDateTime.ToString("O"); + startDateAttributes.Add("value", StartDateTagHelper.Value); + } + } + StartDateTagHelperOutput = await StartDateTagHelper.ProcessAndGetOutputAsync(startDateAttributes, context, "input"); } if (TagHelper.AspForEnd != null) { - var endDateAttributes = new TagHelperAttributeList { { "data-end-date", "true" }, { "type", "hidden" } }; + var endDateAttributes = new TagHelperAttributeList { { "data-hidden-datepicker", "true" }, { "data-end-date", "true" }, { "type", "hidden" } }; EndDateTagHelper = new InputTagHelper(Generator) { ViewContext = TagHelper.ViewContext, @@ -55,6 +76,23 @@ public class AbpDateRangePickerTagHelperService : AbpDatePickerBaseTagHelperServ InputTypeName = "hidden" }; + if (Clock.SupportsMultipleTimezone) + { + if (TagHelper.AspForEnd.Model is DateTime dateTime) + { + EndDateTagHelper.Format = "{0:O}"; + EndDateTagHelper.Value = Clock.ConvertToUserTime(dateTime).ToString("O"); + endDateAttributes.Add("value", EndDateTagHelper.Value); + } + + if (TagHelper.AspForEnd.Model is DateTimeOffset dateTimeOffset) + { + EndDateTagHelper.Format = "{0:O}"; + EndDateTagHelper.Value = Clock.ConvertToUserTime(dateTimeOffset).UtcDateTime.ToString("O"); + endDateAttributes.Add("value", EndDateTagHelper.Value); + } + } + EndDateTagHelperOutput = await EndDateTagHelper.ProcessAndGetOutputAsync(endDateAttributes, context, "input"); } @@ -78,7 +116,7 @@ public class AbpDateRangePickerTagHelperService : AbpDatePickerBaseTagHelperServ protected override int GetOrder() { - return TagHelper.Order; + return TagHelper.AspForStart?.Metadata.Order ?? 0; } protected override void AddBaseTagAttributes(TagHelperAttributeList attributes) @@ -92,7 +130,7 @@ public class AbpDateRangePickerTagHelperService : AbpDatePickerBaseTagHelperServ attributes.Add("data-start-date", convert); } } - + if (TagHelper.AspForEnd?.Model != null && SupportedInputTypes.TryGetValue(TagHelper.AspForEnd.Metadata.ModelType, out var convertFuncEnd)) { @@ -113,4 +151,4 @@ public class AbpDateRangePickerTagHelperService : AbpDatePickerBaseTagHelperServ { return TagHelper.AspForStart ?? TagHelper.AspForEnd; } -} \ No newline at end of file +} diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/bootstrap/modal-manager.js b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/bootstrap/modal-manager.js index 9bba9ee9a9..e11a8f4d99 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/bootstrap/modal-manager.js +++ b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/bootstrap/modal-manager.js @@ -110,7 +110,7 @@ $.validator.defaults.ignore = ''; //TODO: Would be better if we can apply only f _onOpenCallbacks.triggerAll(_publicApi); - if ($firstVisibleInput.data("datepicker")) { + if ($firstVisibleInput.data("datepicker") || $firstVisibleInput.data("daterangepicker")) { return; //don't pop-up date pickers... } diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/datatables/datatables-extensions.js b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/datatables/datatables-extensions.js index 9bbf0abd28..bcb043a196 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/datatables/datatables-extensions.js +++ b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/datatables/datatables-extensions.js @@ -511,22 +511,19 @@ var abp = abp || {}; } }; - var ISOStringToDateTimeLocaleString = function (format) { - return function (data) { - var date = luxon - .DateTime - .fromISO(data, { - locale: abp.localization.currentCulture.name - }); - return format ? date.toLocaleString(format) : date.toLocaleString(); - }; + datatables.defaultRenderers['date'] = function (value) { + if (!value) { + return value; + } else { + return abp.clock.normalizeToLocaleString(value, { year: 'numeric', month: '2-digit', day: '2-digit' }); + } }; - datatables.defaultRenderers['date'] = function (value) { + datatables.defaultRenderers['time'] = function (value) { if (!value) { return value; } else { - return (ISOStringToDateTimeLocaleString())(value); + return abp.clock.normalizeToLocaleString(value, { hour: '2-digit', minute: '2-digit', second: '2-digit' }); } }; @@ -534,7 +531,7 @@ var abp = abp || {}; if (!value) { return value; } else { - return (ISOStringToDateTimeLocaleString(luxon.DateTime.DATETIME_SHORT))(value); + return abp.clock.normalizeToLocaleString(value); } }; diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/date-range-picker/date-range-picker-extensions.js b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/date-range-picker/date-range-picker-extensions.js index 01fe50dec3..e10ceefbf9 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/date-range-picker/date-range-picker-extensions.js +++ b/framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/wwwroot/libs/abp/aspnetcore-mvc-ui-theme-shared/date-range-picker/date-range-picker-extensions.js @@ -752,4 +752,41 @@ $(function () { abp.dom.initializers.initializeDateRangePickers($('body')); }); -})(jQuery); \ No newline at end of file + + $.fn.handleDatepicker = function (datepickerSelector) { + var $this = $(this); + var datepickers = $this.find(datepickerSelector); + $this.find('input[class~="hidden-datepicker"]').remove(); + datepickers.each(function () { + var $this = $(this); + var datepicker = $this.data('daterangepicker'); + if (!datepicker) { + return; + } + if ($this.val() === '') { + return; + } + var name = $this.attr('name') || $this.data('name'); + $this.data('name', name).removeAttr('name'); + if (datepicker.singleDatePicker) { + var startDate = abp.clock.normalizeToString(datepicker.startDate.toDate()); + var startDateInput = $('').attr('type', 'hidden').attr('name', name).val(startDate).addClass('hidden-datepicker'); + $this.after(startDateInput); + } else { + if ($this.data('start-date')) { + var startDate = abp.clock.normalizeToString(datepicker.startDate.toDate()); + var startDateInput = $('').attr('type', 'hidden').attr('name', name).val(startDate).addClass('hidden-datepicker'); + $this.after(startDateInput); + } + if ($this.data('end-date')) { + var endDate = abp.clock.normalizeToString(datepicker.endDate.toDate()); + var endDateInput = $('').attr('type', 'hidden').attr('name', name).val(endDate).addClass('hidden-datepicker'); + $this.after(endDateInput); + } + } + }); + + return this; + }; + +})(jQuery); diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApplicationConfigurations/AbpApplicationConfigurationAppService.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApplicationConfigurations/AbpApplicationConfigurationAppService.cs index 7f41f73165..8dfa51768d 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApplicationConfigurations/AbpApplicationConfigurationAppService.cs +++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/ApplicationConfigurations/AbpApplicationConfigurationAppService.cs @@ -311,7 +311,7 @@ public class AbpApplicationConfigurationAppService : ApplicationService, IAbpApp protected virtual async Task GetTimingConfigAsync() { - var windowsTimeZoneId = await _settingProvider.GetOrNullAsync(TimingSettingNames.TimeZone); + var timeZone = await _settingProvider.GetOrNullAsync(TimingSettingNames.TimeZone); return new TimingDto { @@ -319,13 +319,11 @@ public class AbpApplicationConfigurationAppService : ApplicationService, IAbpApp { Windows = new WindowsTimeZone { - TimeZoneId = windowsTimeZoneId + TimeZoneId = timeZone.IsNullOrWhiteSpace() ? null : _timezoneProvider.IanaToWindows(timeZone) }, Iana = new IanaTimeZone { - TimeZoneName = windowsTimeZoneId.IsNullOrWhiteSpace() - ? null - : _timezoneProvider.WindowsToIana(windowsTimeZoneId!) + TimeZoneName = timeZone } } }; diff --git a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Json/MvcCoreBuilderExtensions.cs b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Json/MvcCoreBuilderExtensions.cs index 8c6edd2eb0..f2bac81316 100644 --- a/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Json/MvcCoreBuilderExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Json/MvcCoreBuilderExtensions.cs @@ -5,6 +5,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Volo.Abp.Json.SystemTextJson; using Volo.Abp.Json.SystemTextJson.JsonConverters; +using Volo.Abp.Json.SystemTextJson.Modifiers; namespace Volo.Abp.AspNetCore.Mvc.Json; @@ -26,6 +27,13 @@ public static class MvcCoreBuilderExtensions options.JsonSerializerOptions.TypeInfoResolver = new AbpDefaultJsonTypeInfoResolver(rootServiceProvider .GetRequiredService>()); + + var dateTimeConverter = rootServiceProvider.GetRequiredService(); + var nullableDateTimeConverter = rootServiceProvider.GetRequiredService(); + + options.JsonSerializerOptions.TypeInfoResolver.As().Modifiers.Add( + new AbpDateTimeConverterModifier(dateTimeConverter, nullableDateTimeConverter) + .CreateModifyAction()); }); return builder; diff --git a/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs index b4d5d4499c..d042bb6026 100644 --- a/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs +++ b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Builder/AbpApplicationBuilderExtensions.cs @@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.RequestLocalization; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.StaticAssets; +using Microsoft.AspNetCore.Timing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; @@ -269,4 +270,14 @@ public static class AbpApplicationBuilderExtensions return app; } + + /// + /// Use this middleware after middleware. + /// + /// + /// + public static IApplicationBuilder UseAbpTimeZone(this IApplicationBuilder app) + { + return app.UseMiddleware(); + } } diff --git a/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Timing/AbpTimeZoneMiddleware.cs b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Timing/AbpTimeZoneMiddleware.cs new file mode 100644 index 0000000000..8ee803feb0 --- /dev/null +++ b/framework/src/Volo.Abp.AspNetCore/Microsoft/AspNetCore/Timing/AbpTimeZoneMiddleware.cs @@ -0,0 +1,82 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.AspNetCore.Middleware; +using Volo.Abp.DependencyInjection; +using Volo.Abp.Settings; +using Volo.Abp.Timing; +using Volo.Abp.Users; + +namespace Microsoft.AspNetCore.Timing; + +public class AbpTimeZoneMiddleware : AbpMiddlewareBase, ITransientDependency +{ + public async override Task InvokeAsync(HttpContext context, RequestDelegate next) + { + if (!context.RequestServices.GetRequiredService().SupportsMultipleTimezone) + { + await next(context); + return; + } + + // Try to get the timezone from the setting system first + var settingProvider = context.RequestServices.GetRequiredService(); + var timezone = await settingProvider.GetOrNullAsync(TimingSettingNames.TimeZone); + + if (timezone.IsNullOrWhiteSpace()) + { + // Try to get the timezone from the HTTP request if the setting is not available + timezone = await GetTimezoneFromRequestAsync(context); + } + + if (timezone.IsNullOrWhiteSpace()) + { + // Try to get the timezone from the current running server if the setting and request are not available + timezone = await GetLocalTimeZoneAsync(); + } + + var currentTimezoneProvider = context.RequestServices.GetRequiredService(); + using (currentTimezoneProvider.Change(timezone)) + { + await next(context); + } + } + + protected virtual async Task GetTimezoneFromRequestAsync(HttpContext context) + { + var timeZoneSources = new Func>[] + { + ctx => Task.FromResult(ctx.Request.Headers[TimeZoneConsts.DefaultTimeZoneKey].FirstOrDefault()), + ctx => Task.FromResult(ctx.Request.Query[TimeZoneConsts.DefaultTimeZoneKey].ToString()), + async ctx => ctx.Request.HasFormContentType + ? (await ctx.Request.ReadFormAsync())[TimeZoneConsts.DefaultTimeZoneKey].ToString() + : null, + ctx => Task.FromResult(ctx.Request.Cookies[TimeZoneConsts.DefaultTimeZoneKey]?.ToString()), + }; + + foreach (var source in timeZoneSources) + { + var timezone = await source(context); + if (!string.IsNullOrEmpty(timezone)) + { + return timezone; + } + } + + return null; + } + + protected virtual Task GetLocalTimeZoneAsync() + { + if (TimeZoneInfo.Local.HasIanaId) + { + return Task.FromResult(TimeZoneInfo.Local.Id); + } + + return TimeZoneInfo.TryConvertWindowsIdToIanaId(TimeZoneInfo.Local.Id, out var ianaName) + ? Task.FromResult(ianaName) + : Task.FromResult(null); + } +} diff --git a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyBase.cs b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyBase.cs index 01c1e2a720..d09f97b24c 100644 --- a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyBase.cs +++ b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyBase.cs @@ -20,6 +20,7 @@ using Volo.Abp.Json; using Volo.Abp.MultiTenancy; using Volo.Abp.Reflection; using Volo.Abp.Threading; +using Volo.Abp.Timing; using Volo.Abp.Tracing; namespace Volo.Abp.Http.Client.ClientProxying; @@ -33,6 +34,7 @@ public class ClientProxyBase : ITransientDependency protected ICorrelationIdProvider CorrelationIdProvider => LazyServiceProvider.LazyGetRequiredService(); protected ICurrentTenant CurrentTenant => LazyServiceProvider.LazyGetRequiredService(); protected IOptions AbpCorrelationIdOptions => LazyServiceProvider.LazyGetRequiredService>(); + protected ICurrentTimezoneProvider CurrentTimezoneProvider => LazyServiceProvider.LazyGetRequiredService(); protected IProxyHttpClientFactory HttpClientFactory => LazyServiceProvider.LazyGetRequiredService(); protected IRemoteServiceConfigurationProvider RemoteServiceConfigurationProvider => LazyServiceProvider.LazyGetRequiredService(); protected IOptions ClientOptions => LazyServiceProvider.LazyGetRequiredService>(); @@ -337,6 +339,12 @@ public class ClientProxyBase : ITransientDependency //X-Requested-With requestMessage.Headers.Add("X-Requested-With", "XMLHttpRequest"); + + //Timezone + if (!CurrentTimezoneProvider.TimeZone.IsNullOrWhiteSpace()) + { + requestMessage.Headers.Add(TimeZoneConsts.DefaultTimeZoneKey, CurrentTimezoneProvider.TimeZone); + } } protected virtual StringSegment RemoveQuotes(StringSegment input) diff --git a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyRequestPayloadBuilder.cs b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyRequestPayloadBuilder.cs index c24404918e..91fc6f33bf 100644 --- a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyRequestPayloadBuilder.cs +++ b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyRequestPayloadBuilder.cs @@ -15,6 +15,7 @@ using Volo.Abp.Http.Client.Proxying; using Volo.Abp.Http.Modeling; using Volo.Abp.Http.ProxyScripting.Generators; using Volo.Abp.Json; +using Volo.Abp.Timing; namespace Volo.Abp.Http.Client.ClientProxying; @@ -33,9 +34,15 @@ public class ClientProxyRequestPayloadBuilder : ITransientDependency protected AbpHttpClientProxyingOptions HttpClientProxyingOptions { get; } - public ClientProxyRequestPayloadBuilder(IServiceScopeFactory serviceScopeFactory, IOptions httpClientProxyingOptions) + protected IClock Clock { get; } + + public ClientProxyRequestPayloadBuilder( + IServiceScopeFactory serviceScopeFactory, + IOptions httpClientProxyingOptions, + IClock clock) { ServiceScopeFactory = serviceScopeFactory; + Clock = clock; HttpClientProxyingOptions = httpClientProxyingOptions.Value; } @@ -156,12 +163,12 @@ public class ClientProxyRequestPayloadBuilder : ITransientDependency { foreach (var item in (IEnumerable) value) { - formData.Add(new StringContent(item.ToString()!, Encoding.UTF8), parameter.Name); + formData.Add(new StringContent(await ConvertValueToStringAsync(item), Encoding.UTF8), parameter.Name); } } else { - formData.Add(new StringContent(value.ToString()!, Encoding.UTF8), parameter.Name); + formData.Add(new StringContent(await ConvertValueToStringAsync(value), Encoding.UTF8), parameter.Name); } } @@ -172,4 +179,19 @@ public class ClientProxyRequestPayloadBuilder : ITransientDependency { return await converter.ConvertAsync(actionApiDescription, parameterApiDescription, value); } + + protected virtual Task ConvertValueToStringAsync(object value) + { + if (value is DateTime dateTimeValue) + { + if (Clock.SupportsMultipleTimezone || dateTimeValue.Kind == DateTimeKind.Utc) + { + return Task.FromResult(dateTimeValue.ToUniversalTime().ToString("O")); + } + + return Task.FromResult(dateTimeValue.ToString("yyyy-MM-ddTHH:mm:ss.fffffff").TrimEnd('0').TrimEnd('.')); + } + + return Task.FromResult(value.ToString()!); + } } diff --git a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyUrlBuilder.cs b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyUrlBuilder.cs index 65703dc56b..5be598af20 100644 --- a/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyUrlBuilder.cs +++ b/framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyUrlBuilder.cs @@ -14,6 +14,7 @@ using Volo.Abp.Http.Client.Proxying; using Volo.Abp.Http.Modeling; using Volo.Abp.Http.ProxyScripting.Generators; using Volo.Abp.Localization; +using Volo.Abp.Timing; namespace Volo.Abp.Http.Client.ClientProxying; @@ -36,11 +37,16 @@ public class ClientProxyUrlBuilder : ITransientDependency protected IServiceScopeFactory ServiceScopeFactory { get; } protected AbpHttpClientProxyingOptions HttpClientProxyingOptions { get; } + protected IClock Clock { get; } - public ClientProxyUrlBuilder(IServiceScopeFactory serviceScopeFactory, IOptions httpClientProxyingOptions) + public ClientProxyUrlBuilder( + IServiceScopeFactory serviceScopeFactory, + IOptions httpClientProxyingOptions, + IClock clock) { ServiceScopeFactory = serviceScopeFactory; HttpClientProxyingOptions = httpClientProxyingOptions.Value; + Clock = clock; } public async Task GenerateUrlWithParametersAsync(ActionApiDescriptionModel action, IReadOnlyDictionary methodArguments, ApiVersionInfo apiVersion) @@ -218,13 +224,18 @@ public class ClientProxyUrlBuilder : ITransientDependency return true; } - protected virtual Task ConvertValueToStringAsync(object? value) + protected virtual Task ConvertValueToStringAsync(object value) { if (value is DateTime dateTimeValue) { - return Task.FromResult(dateTimeValue.ToUniversalTime().ToString("O"))!; + if (Clock.SupportsMultipleTimezone || dateTimeValue.Kind == DateTimeKind.Utc) + { + return Task.FromResult(dateTimeValue.ToUniversalTime().ToString("O")); + } + + return Task.FromResult(dateTimeValue.ToString("yyyy-MM-ddTHH:mm:ss.fffffff").TrimEnd('0').TrimEnd('.')); } - return Task.FromResult(value?.ToString()); + return Task.FromResult(value.ToString()!); } -} \ No newline at end of file +} diff --git a/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpDateTimeConverter.cs b/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpDateTimeConverter.cs index effda40057..c95660e484 100644 --- a/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpDateTimeConverter.cs +++ b/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpDateTimeConverter.cs @@ -19,6 +19,7 @@ public class AbpDateTimeConverter : DateTimeConverterBase, ITransientDependency private readonly CultureInfo _culture = CultureInfo.InvariantCulture; private readonly IClock _clock; private readonly AbpJsonOptions _options; + private bool _skipDateTimeNormalization; public AbpDateTimeConverter(IClock clock, IOptions options) { @@ -26,6 +27,12 @@ public class AbpDateTimeConverter : DateTimeConverterBase, ITransientDependency _options = options.Value; } + public virtual AbpDateTimeConverter SkipDateTimeNormalization() + { + _skipDateTimeNormalization = true; + return this; + } + public override bool CanConvert(Type objectType) { return objectType == typeof(DateTime) || objectType == typeof(DateTime?); @@ -46,7 +53,7 @@ public class AbpDateTimeConverter : DateTimeConverterBase, ITransientDependency if (reader.TokenType == JsonToken.Date) { - return _clock.Normalize(reader.Value!.To()); + return Normalize(reader.Value!.To()); } if (reader.TokenType != JsonToken.String) @@ -67,20 +74,20 @@ public class AbpDateTimeConverter : DateTimeConverterBase, ITransientDependency { if (DateTime.TryParseExact(dateText, format, _culture, _dateTimeStyles, out var d1)) { - return _clock.Normalize(d1); + return Normalize(d1); } } } var date = DateTime.Parse(dateText!, _culture, _dateTimeStyles); - return _clock.Normalize(date); + return Normalize(date); } public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value != null) { - value = _clock.Normalize(value.To()); + value = Normalize(value.To()); } if (value is DateTime dateTime) @@ -111,4 +118,11 @@ public class AbpDateTimeConverter : DateTimeConverterBase, ITransientDependency return ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault(member) == null; } + + protected virtual DateTime Normalize(DateTime dateTime) + { + return _skipDateTimeNormalization + ? dateTime + : _clock.Normalize(dateTime); + } } diff --git a/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpJsonNewtonsoftModule.cs b/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpJsonNewtonsoftModule.cs index 6f93a6c54e..ea35831d86 100644 --- a/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpJsonNewtonsoftModule.cs +++ b/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpJsonNewtonsoftModule.cs @@ -13,7 +13,8 @@ public class AbpJsonNewtonsoftModule : AbpModule context.Services.AddOptions() .Configure((options, rootServiceProvider) => { - options.JsonSerializerSettings.ContractResolver = new AbpCamelCasePropertyNamesContractResolver(rootServiceProvider.GetRequiredService()); + options.JsonSerializerSettings.ContractResolver = new AbpCamelCasePropertyNamesContractResolver( + rootServiceProvider.GetRequiredService().SkipDateTimeNormalization()); }); } } diff --git a/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpNewtonsoftJsonSerializer.cs b/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpNewtonsoftJsonSerializer.cs index 0450064f2f..8184ee6d45 100644 --- a/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpNewtonsoftJsonSerializer.cs +++ b/framework/src/Volo.Abp.Json.Newtonsoft/Volo/Abp/Json/Newtonsoft/AbpNewtonsoftJsonSerializer.cs @@ -86,7 +86,8 @@ public class AbpNewtonsoftJsonSerializer : IJsonSerializer, ITransientDependency if (!camelCase) { //Default contract resolver is AbpCamelCasePropertyNamesContractResolver} - settings.ContractResolver = new AbpDefaultContractResolver(RootServiceProvider.GetRequiredService()); + settings.ContractResolver = new AbpDefaultContractResolver(RootServiceProvider + .GetRequiredService().SkipDateTimeNormalization()); } if (indented) diff --git a/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/AbpJsonSystemTextJsonModule.cs b/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/AbpJsonSystemTextJsonModule.cs index 498dedd8cd..0a5066cec1 100644 --- a/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/AbpJsonSystemTextJsonModule.cs +++ b/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/AbpJsonSystemTextJsonModule.cs @@ -29,14 +29,13 @@ public class AbpJsonSystemTextJsonModule : AbpModule options.JsonSerializerOptions.TypeInfoResolver = new AbpDefaultJsonTypeInfoResolver(rootServiceProvider .GetRequiredService>()); - }); - context.Services.AddOptions() - .Configure((options, rootServiceProvider) => - { - options.Modifiers.Add(new AbpDateTimeConverterModifier( - rootServiceProvider.GetRequiredService(), - rootServiceProvider.GetRequiredService()).CreateModifyAction()); + var dateTimeConverter = rootServiceProvider.GetRequiredService().SkipDateTimeNormalization(); + var nullableDateTimeConverter = rootServiceProvider.GetRequiredService().SkipDateTimeNormalization(); + + options.JsonSerializerOptions.TypeInfoResolver.As().Modifiers.Add( + new AbpDateTimeConverterModifier(dateTimeConverter, nullableDateTimeConverter) + .CreateModifyAction()); }); } } diff --git a/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpDateTimeConverter.cs b/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpDateTimeConverter.cs index a8653bb54a..3feea8d299 100644 --- a/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpDateTimeConverter.cs +++ b/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpDateTimeConverter.cs @@ -13,6 +13,7 @@ public class AbpDateTimeConverter : JsonConverter, ITransientDependenc { private readonly IClock _clock; private readonly AbpJsonOptions _options; + private bool _skipDateTimeNormalization; public AbpDateTimeConverter(IClock clock, IOptions abpJsonOptions) { @@ -20,6 +21,12 @@ public class AbpDateTimeConverter : JsonConverter, ITransientDependenc _options = abpJsonOptions.Value; } + public virtual AbpDateTimeConverter SkipDateTimeNormalization() + { + _skipDateTimeNormalization = true; + return this; + } + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (_options.InputDateTimeFormats.Any()) @@ -31,7 +38,7 @@ public class AbpDateTimeConverter : JsonConverter, ITransientDependenc var s = reader.GetString(); if (DateTime.TryParseExact(s, format, CultureInfo.CurrentUICulture, DateTimeStyles.None, out var d1)) { - return _clock.Normalize(d1); + return Normalize(d1); } } } @@ -43,7 +50,7 @@ public class AbpDateTimeConverter : JsonConverter, ITransientDependenc if (reader.TryGetDateTime(out var d3)) { - return _clock.Normalize(d3); + return Normalize(d3); } var dateText = reader.GetString(); @@ -51,7 +58,7 @@ public class AbpDateTimeConverter : JsonConverter, ITransientDependenc { if (DateTime.TryParse(dateText, CultureInfo.CurrentUICulture, DateTimeStyles.None, out var d4)) { - return _clock.Normalize(d4); + return Normalize(d4); } } @@ -62,11 +69,16 @@ public class AbpDateTimeConverter : JsonConverter, ITransientDependenc { if (_options.OutputDateTimeFormat.IsNullOrWhiteSpace()) { - writer.WriteStringValue(_clock.Normalize(value)); + writer.WriteStringValue(Normalize(value)); } else { - writer.WriteStringValue(_clock.Normalize(value).ToString(_options.OutputDateTimeFormat, CultureInfo.CurrentUICulture)); + writer.WriteStringValue(Normalize(value).ToString(_options.OutputDateTimeFormat, CultureInfo.CurrentUICulture)); } } + + protected virtual DateTime Normalize(DateTime dateTime) + { + return _skipDateTimeNormalization ? dateTime : _clock.Normalize(dateTime); + } } diff --git a/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpNullableDateTimeConverter.cs b/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpNullableDateTimeConverter.cs index e8a94892da..e73f39d097 100644 --- a/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpNullableDateTimeConverter.cs +++ b/framework/src/Volo.Abp.Json.SystemTextJson/Volo/Abp/Json/SystemTextJson/JsonConverters/AbpNullableDateTimeConverter.cs @@ -13,6 +13,7 @@ public class AbpNullableDateTimeConverter : JsonConverter, ITransient { private readonly IClock _clock; private readonly AbpJsonOptions _options; + private bool _skipDateTimeNormalization; public AbpNullableDateTimeConverter(IClock clock, IOptions abpJsonOptions) { @@ -20,6 +21,12 @@ public class AbpNullableDateTimeConverter : JsonConverter, ITransient _options = abpJsonOptions.Value; } + public virtual AbpNullableDateTimeConverter SkipDateTimeNormalization() + { + _skipDateTimeNormalization = true; + return this; + } + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (_options.InputDateTimeFormats.Any()) @@ -31,7 +38,7 @@ public class AbpNullableDateTimeConverter : JsonConverter, ITransient var s = reader.GetString(); if (DateTime.TryParseExact(s, format, CultureInfo.CurrentUICulture, DateTimeStyles.None, out var d1)) { - return _clock.Normalize(d1); + return Normalize(d1); } } } @@ -43,7 +50,7 @@ public class AbpNullableDateTimeConverter : JsonConverter, ITransient if (reader.TryGetDateTime(out var d2)) { - return _clock.Normalize(d2); + return Normalize(d2); } var dateText = reader.GetString(); @@ -51,7 +58,7 @@ public class AbpNullableDateTimeConverter : JsonConverter, ITransient { if (DateTime.TryParse(dateText, CultureInfo.CurrentUICulture, DateTimeStyles.None, out var d3)) { - return _clock.Normalize(d3); + return Normalize(d3); } } @@ -68,12 +75,17 @@ public class AbpNullableDateTimeConverter : JsonConverter, ITransient { if (_options.OutputDateTimeFormat.IsNullOrWhiteSpace()) { - writer.WriteStringValue(_clock.Normalize(value.Value)); + writer.WriteStringValue(Normalize(value.Value)); } else { - writer.WriteStringValue(_clock.Normalize(value.Value).ToString(_options.OutputDateTimeFormat, CultureInfo.CurrentUICulture)); + writer.WriteStringValue(Normalize(value.Value).ToString(_options.OutputDateTimeFormat, CultureInfo.CurrentUICulture)); } } } + + protected virtual DateTime Normalize(DateTime dateTime) + { + return _skipDateTimeNormalization ? dateTime : _clock.Normalize(dateTime); + } } diff --git a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/Clock.cs b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/Clock.cs index 8788a2b5db..36bee9e8fd 100644 --- a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/Clock.cs +++ b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/Clock.cs @@ -7,9 +7,16 @@ namespace Volo.Abp.Timing; public class Clock : IClock, ITransientDependency { protected AbpClockOptions Options { get; } + protected ICurrentTimezoneProvider CurrentTimezoneProvider { get; } + protected ITimezoneProvider TimezoneProvider { get; } - public Clock(IOptions options) + public Clock( + IOptions options, + ICurrentTimezoneProvider currentTimezoneProvider, + ITimezoneProvider timezoneProvider) { + CurrentTimezoneProvider = currentTimezoneProvider; + TimezoneProvider = timezoneProvider; Options = options.Value; } @@ -19,6 +26,11 @@ public class Clock : IClock, ITransientDependency public virtual bool SupportsMultipleTimezone => Options.Kind == DateTimeKind.Utc; + /// + /// Normalizes given . + /// + /// DateTime to be normalized. + /// Normalized DateTime public virtual DateTime Normalize(DateTime dateTime) { if (Kind == DateTimeKind.Unspecified || Kind == dateTime.Kind) @@ -38,4 +50,58 @@ public class Clock : IClock, ITransientDependency return DateTime.SpecifyKind(dateTime, Kind); } + + /// + /// Converts given UTC to user's time zone. + /// + /// DateTime to be normalized. + /// Converted DateTime + public virtual DateTime ConvertToUserTime(DateTime utcDateTime) + { + if (!SupportsMultipleTimezone || + utcDateTime.Kind != DateTimeKind.Utc || + CurrentTimezoneProvider.TimeZone.IsNullOrWhiteSpace()) + { + return utcDateTime; + } + + var timezoneInfo = TimezoneProvider.GetTimeZoneInfo(CurrentTimezoneProvider.TimeZone); + return TimeZoneInfo.ConvertTime(utcDateTime, timezoneInfo); + } + + /// + /// Converts given to user's time zone. + /// + /// DateTimeOffset to be normalized. + /// Converted DateTimeOffset + public virtual DateTimeOffset ConvertToUserTime(DateTimeOffset dateTimeOffset) + { + if (!SupportsMultipleTimezone || + CurrentTimezoneProvider.TimeZone.IsNullOrWhiteSpace()) + { + return dateTimeOffset; + } + + var timezoneInfo = TimezoneProvider.GetTimeZoneInfo(CurrentTimezoneProvider.TimeZone); + return TimeZoneInfo.ConvertTime(dateTimeOffset, timezoneInfo); + } + + /// + /// Converts given to UTC if the given time is not UTC and the current clock provider supports multiple time zones. + /// + /// DateTime to be normalized. + /// Converted DateTime + public DateTime ConvertToUtc(DateTime dateTime) + { + if (!SupportsMultipleTimezone || + dateTime.Kind == DateTimeKind.Utc || + CurrentTimezoneProvider.TimeZone.IsNullOrWhiteSpace()) + { + return dateTime; + } + + var timezoneInfo = TimezoneProvider.GetTimeZoneInfo(CurrentTimezoneProvider.TimeZone); + dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified); + return TimeZoneInfo.ConvertTimeToUtc(dateTime, timezoneInfo); + } } diff --git a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/CurrentTimezoneProvider.cs b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/CurrentTimezoneProvider.cs new file mode 100644 index 0000000000..12781d4321 --- /dev/null +++ b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/CurrentTimezoneProvider.cs @@ -0,0 +1,20 @@ +using System.Threading; +using Volo.Abp.DependencyInjection; + +namespace Volo.Abp.Timing; + +public class CurrentTimezoneProvider : ICurrentTimezoneProvider, ISingletonDependency +{ + public string? TimeZone + { + get => _currentScope.Value; + set => _currentScope.Value = value; + } + + private readonly AsyncLocal _currentScope; + + public CurrentTimezoneProvider() + { + _currentScope = new AsyncLocal(); + } +} diff --git a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/CurrentTimezoneProviderExtensions.cs b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/CurrentTimezoneProviderExtensions.cs new file mode 100644 index 0000000000..2fc79289ad --- /dev/null +++ b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/CurrentTimezoneProviderExtensions.cs @@ -0,0 +1,18 @@ +using System; + +namespace Volo.Abp.Timing; + +public static class CurrentTimezoneProviderExtensions +{ + public static IDisposable Change(this ICurrentTimezoneProvider currentTimezoneProvider, string? timeZone) + { + var parentScope = currentTimezoneProvider.TimeZone; + currentTimezoneProvider.TimeZone = timeZone; + + return new DisposeAction>(static (state) => + { + var (currentTimezoneProvider, parentScope) = state; + currentTimezoneProvider.TimeZone = parentScope; + }, (currentTimezoneProvider, parentScope)); + } +} diff --git a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/IClientTimezoneProvider.cs b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/IClientTimezoneProvider.cs new file mode 100644 index 0000000000..69c2835adc --- /dev/null +++ b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/IClientTimezoneProvider.cs @@ -0,0 +1,6 @@ +namespace Volo.Abp.Timing; + +public interface ICurrentTimezoneProvider +{ + string? TimeZone { get; set; } +} diff --git a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/IClock.cs b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/IClock.cs index 33db4b45a8..7bf83dc7e0 100644 --- a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/IClock.cs +++ b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/IClock.cs @@ -25,4 +25,25 @@ public interface IClock /// DateTime to be normalized. /// Normalized DateTime DateTime Normalize(DateTime dateTime); + + /// + /// Converts given UTC to user's time zone. + /// + /// DateTime to be normalized. + /// Converted DateTime + DateTime ConvertToUserTime(DateTime utcDateTime); + + /// + /// Converts given to user's time zone. + /// + /// DateTimeOffset to be normalized. + /// Converted DateTimeOffset + DateTimeOffset ConvertToUserTime(DateTimeOffset dateTimeOffset); + + /// + /// Converts given to UTC if the given time is not UTC and the current clock provider supports multiple time zones. + /// + /// DateTime to be normalized. + /// Converted DateTime + DateTime ConvertToUtc(DateTime dateTime); } diff --git a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TZConvertTimezoneProvider.cs b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TZConvertTimezoneProvider.cs index 70d19090e2..565c04c6fa 100644 --- a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TZConvertTimezoneProvider.cs +++ b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TZConvertTimezoneProvider.cs @@ -15,7 +15,7 @@ public class TZConvertTimezoneProvider : ITimezoneProvider, ITransientDependency public virtual List GetIanaTimezones() { - return TZConvert.KnownIanaTimeZoneNames.OrderBy(x => x).Select(x => new NameValue(x, x)).ToList(); + return TZConvert.KnownIanaTimeZoneNames.OrderBy(x => x).Where(x => x.Contains("/") && !x.Contains("Etc") || x == "UTC").Select(x => new NameValue(x, x)).ToList(); } public virtual string WindowsToIana(string windowsTimeZoneId) diff --git a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TimeZoneConsts.cs b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TimeZoneConsts.cs new file mode 100644 index 0000000000..211247f5aa --- /dev/null +++ b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TimeZoneConsts.cs @@ -0,0 +1,6 @@ +namespace Volo.Abp.Timing; + +public class TimeZoneConsts +{ + public const string DefaultTimeZoneKey = "__timezone"; +} diff --git a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TimingSettingProvider.cs b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TimingSettingProvider.cs index 066747df94..343e20feb5 100644 --- a/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TimingSettingProvider.cs +++ b/framework/src/Volo.Abp.Timing/Volo/Abp/Timing/TimingSettingProvider.cs @@ -10,7 +10,7 @@ public class TimingSettingProvider : SettingDefinitionProvider { context.Add( new SettingDefinition(TimingSettingNames.TimeZone, - "UTC", + "", L("DisplayName:Abp.Timing.Timezone"), L("Description:Abp.Timing.Timezone"), isVisibleToClients: true) diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcTestModule.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcTestModule.cs index 0e13746d66..1c705d8df3 100644 --- a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcTestModule.cs +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/AbpAspNetCoreMvcTestModule.cs @@ -159,6 +159,7 @@ public class AbpAspNetCoreMvcTestModule : AbpModule app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); + app.UseAbpTimeZone(); app.UseAuditing(); app.UseUnitOfWork(); app.UseConfiguredEndpoints(); diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Timing/AbpTimeZoneMiddleware_Tests.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Timing/AbpTimeZoneMiddleware_Tests.cs new file mode 100644 index 0000000000..7f12e5a07d --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Timing/AbpTimeZoneMiddleware_Tests.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Shouldly; +using Volo.Abp.Settings; +using Volo.Abp.Timing; +using Xunit; + +namespace Volo.Abp.AspNetCore.Mvc.Timing; + +public class AbpTimeZoneMiddleware_Tests : AspNetCoreMvcTestBase +{ + private readonly ICurrentTimezoneProvider _currentTimezoneProvider; + private readonly ITimezoneProvider _timezoneProvider; + public AbpTimeZoneMiddleware_Tests() + { + _currentTimezoneProvider = GetRequiredService(); + _timezoneProvider = GetRequiredService(); + } + + protected override void ConfigureServices(IServiceCollection services) + { + services.Configure(options => + { + options.Kind = DateTimeKind.Utc; + }); + } + + [Fact] + public async Task Should_Override_TimeZone_Setting_By_Request() + { + using (_currentTimezoneProvider.Change("UTC")) + { + var result = await Client.GetStringAsync("api/timing-test"); + result.ShouldBe(GetLocalTimeZone()); + } + + // Query string + using (_currentTimezoneProvider.Change("UTC")) + { + var result = await Client.GetStringAsync("api/timing-test?__timezone=Europe/Istanbul"); + result.ShouldBe("Europe/Istanbul"); + } + + // Header + using (_currentTimezoneProvider.Change("UTC")) + { + Client.DefaultRequestHeaders.Add("__timezone", "Asia/Shanghai"); + var result = await Client.GetStringAsync("api/timing-test"); + result.ShouldBe("Asia/Shanghai"); + } + + // Form + using (_currentTimezoneProvider.Change("UTC")) + { + Client.DefaultRequestHeaders.Remove("__timezone"); + var result = await Client.PostAsync("api/timing-test", new FormUrlEncodedContent(new[] {new KeyValuePair("__timezone", "Europe/Germany")})); + (await result.Content.ReadAsStringAsync()).ShouldBe("Europe/Germany"); + } + + // Cookie + using (_currentTimezoneProvider.Change("UTC")) + { + Client.DefaultRequestHeaders.Remove("__timezone"); + Client.DefaultRequestHeaders.Add("Cookie", "__timezone=Europe/Istanbul"); + var result = await Client.GetStringAsync("api/timing-test"); + result.ShouldBe("Europe/Istanbul"); + } + } + + private string GetLocalTimeZone() + { + if (TimeZoneInfo.Local.HasIanaId) + { + return TimeZoneInfo.Local.Id; + } + + return TimeZoneInfo.TryConvertWindowsIdToIanaId(TimeZoneInfo.Local.Id, out var ianaName) + ? ianaName + : null; + } +} + + +public class AbpTimeZoneMiddleware_With_SettingValue_Tests : AspNetCoreMvcTestBase +{ + private readonly ICurrentTimezoneProvider _currentTimezoneProvider; + public AbpTimeZoneMiddleware_With_SettingValue_Tests() + { + _currentTimezoneProvider = GetRequiredService(); + } + + protected override void ConfigureServices(IServiceCollection services) + { + var settingStore = Substitute.For(); + settingStore.GetOrNullAsync(TimingSettingNames.TimeZone).Returns("Asia/Shanghai"); + services.AddSingleton(settingStore); + + services.Configure(options => + { + options.Kind = DateTimeKind.Utc; + }); + } + + [Fact] + public async Task Should_Not_Override_TimeZone_Setting_By_Request() + { + using (_currentTimezoneProvider.Change("UTC")) + { + var result = await Client.GetStringAsync("api/timing-test"); + result.ShouldBe("Asia/Shanghai"); + } + + // Query string + using (_currentTimezoneProvider.Change("UTC")) + { + var result = await Client.GetStringAsync("api/timing-test?__timezone=Europe/Istanbul"); + result.ShouldBe("Asia/Shanghai"); + } + + // Header + using (_currentTimezoneProvider.Change("UTC")) + { + Client.DefaultRequestHeaders.Add("__timezone", "Europe/Istanbul"); + var result = await Client.GetStringAsync("api/timing-test"); + result.ShouldBe("Asia/Shanghai"); + } + + // Form + using (_currentTimezoneProvider.Change("UTC")) + { + Client.DefaultRequestHeaders.Remove("__timezone"); + var result = await Client.PostAsync("api/timing-test", new FormUrlEncodedContent(new[] {new KeyValuePair("__timezone", "Europe/Istanbul")})); + (await result.Content.ReadAsStringAsync()).ShouldBe("Asia/Shanghai"); + } + + // Cookie + using (_currentTimezoneProvider.Change("UTC")) + { + Client.DefaultRequestHeaders.Remove("__timezone"); + Client.DefaultRequestHeaders.Add("Cookie", "__timezone=Europe/Istanbul"); + var result = await Client.GetStringAsync("api/timing-test"); + result.ShouldBe("Asia/Shanghai"); + } + } +} diff --git a/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Timing/TimingTestController.cs b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Timing/TimingTestController.cs new file mode 100644 index 0000000000..a509e62ec5 --- /dev/null +++ b/framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/Timing/TimingTestController.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.Mvc; +using Volo.Abp.Timing; + +namespace Volo.Abp.AspNetCore.Mvc.Timing; + +[Route("api/timing-test")] +public class UnitOfWorkTestController : AbpController +{ + private readonly ICurrentTimezoneProvider _currentTimezoneProvider; + + public UnitOfWorkTestController(ICurrentTimezoneProvider currentTimezoneProvider) + { + _currentTimezoneProvider = currentTimezoneProvider; + } + + [HttpGet] + public ActionResult GetAsync() + { + return Content(_currentTimezoneProvider.TimeZone ?? "null"); + } + + [HttpPost] + public ActionResult PostAsync() + { + return Content(_currentTimezoneProvider.TimeZone ?? "null"); + } +} diff --git a/framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonNewtonsoftTestModule.cs b/framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonNewtonsoftTestModule.cs deleted file mode 100644 index 42559397da..0000000000 --- a/framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonNewtonsoftTestModule.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Volo.Abp.Autofac; -using Volo.Abp.Json.Newtonsoft; -using Volo.Abp.Json.SystemTextJson; -using Volo.Abp.Modularity; - -namespace Volo.Abp.Json; - -[DependsOn( - typeof(AbpAutofacModule), - typeof(AbpJsonSystemTextJsonModule), - typeof(AbpTestBaseModule) -)] -public class AbpJsonSystemTextJsonTestModule : AbpModule -{ - -} - -[DependsOn( - typeof(AbpAutofacModule), - typeof(AbpJsonNewtonsoftModule), - typeof(AbpTestBaseModule) -)] -public class AbpJsonNewtonsoftTestModule : AbpModule -{ - -} diff --git a/framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonSystemTextJsonTestBase.cs b/framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonTestBase.cs similarity index 100% rename from framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonSystemTextJsonTestBase.cs rename to framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonTestBase.cs diff --git a/framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonTestModule.cs b/framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonTestModule.cs new file mode 100644 index 0000000000..121ec62a85 --- /dev/null +++ b/framework/test/Volo.Abp.Json.Tests/Volo/Abp/Json/AbpJsonTestModule.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using Microsoft.Extensions.DependencyInjection; +using Volo.Abp.Autofac; +using Volo.Abp.Json.Newtonsoft; +using Volo.Abp.Json.SystemTextJson; +using Volo.Abp.Json.SystemTextJson.JsonConverters; +using Volo.Abp.Json.SystemTextJson.Modifiers; +using Volo.Abp.Modularity; + +namespace Volo.Abp.Json; + +[DependsOn( + typeof(AbpAutofacModule), + typeof(AbpJsonSystemTextJsonModule), + typeof(AbpTestBaseModule) +)] +public class AbpJsonSystemTextJsonTestModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + context.Services.AddOptions() + .Configure((options, rootServiceProvider) => + { + if (options.JsonSerializerOptions.TypeInfoResolver != null) + { + var modifiers = options.JsonSerializerOptions.TypeInfoResolver.As().Modifiers; + modifiers.RemoveAll(x => x.Target?.GetType() == typeof(AbpDateTimeConverterModifier)); + modifiers.Add(new AbpDateTimeConverterModifier( + rootServiceProvider.GetRequiredService(), + rootServiceProvider.GetRequiredService()).CreateModifyAction()); + } + }); + } +} + +[DependsOn( + typeof(AbpAutofacModule), + typeof(AbpJsonNewtonsoftModule), + typeof(AbpTestBaseModule) +)] +public class AbpJsonNewtonsoftTestModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + context.Services.AddOptions() + .Configure((options, rootServiceProvider) => + { + options.JsonSerializerSettings.ContractResolver = new AbpCamelCasePropertyNamesContractResolver( + rootServiceProvider.GetRequiredService()); + }); + } +} diff --git a/framework/test/Volo.Abp.Timing.Tests/Volo.Abp.Timing.Tests.csproj b/framework/test/Volo.Abp.Timing.Tests/Volo.Abp.Timing.Tests.csproj new file mode 100644 index 0000000000..58bc261247 --- /dev/null +++ b/framework/test/Volo.Abp.Timing.Tests/Volo.Abp.Timing.Tests.csproj @@ -0,0 +1,16 @@ + + + + + + net9.0 + + + + + + + + + + diff --git a/framework/test/Volo.Abp.Timing.Tests/Volo/Abp/Timing/AbpTimingTestModule.cs b/framework/test/Volo.Abp.Timing.Tests/Volo/Abp/Timing/AbpTimingTestModule.cs new file mode 100644 index 0000000000..c416477f53 --- /dev/null +++ b/framework/test/Volo.Abp.Timing.Tests/Volo/Abp/Timing/AbpTimingTestModule.cs @@ -0,0 +1,14 @@ +using Volo.Abp.Modularity; + +namespace Volo.Abp.Timing; + +[DependsOn( + typeof(AbpTimingModule), + typeof(AbpTestBaseModule) +)] +public class AbpTimingTestModule : AbpModule +{ + public override void ConfigureServices(ServiceConfigurationContext context) + { + } +} diff --git a/framework/test/Volo.Abp.Timing.Tests/Volo/Abp/Timing/Clock_Default_Tests.cs b/framework/test/Volo.Abp.Timing.Tests/Volo/Abp/Timing/Clock_Default_Tests.cs new file mode 100644 index 0000000000..1904518180 --- /dev/null +++ b/framework/test/Volo.Abp.Timing.Tests/Volo/Abp/Timing/Clock_Default_Tests.cs @@ -0,0 +1,110 @@ +using System; +using Shouldly; +using Volo.Abp.Testing; +using Xunit; + +namespace Volo.Abp.Timing; + +public class Clock_Default_Tests : AbpIntegratedTest +{ + private readonly IClock _clock; + private readonly ICurrentTimezoneProvider _currentTimezoneProvider; + + public Clock_Default_Tests() + { + _clock = GetRequiredService(); + _currentTimezoneProvider = GetRequiredService(); + } + + [Fact] + public void ConvertTo_Test() + { + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc); + var convertedDateTime = _clock.ConvertToUserTime(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Utc); + convertedDateTime.ToString("O").ShouldBe("2025-03-01T05:30:00.0000000Z"); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Local); + var convertedDateTime = _clock.ConvertToUserTime(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Local); + convertedDateTime.ToString("O").ShouldBe(dateTime.ToString("O")); + } + + using(_currentTimezoneProvider.Change(null)) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Local); + var convertedDateTime = _clock.ConvertToUserTime(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Local); + convertedDateTime.ToString("O").ShouldBe(dateTime.ToString("O")); + } + } + + [Fact] + public void ConvertTo_DateTimeOffset_Test() + { + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTimeOffset = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc), TimeSpan.Zero); + var convertedDateTimeOffset = _clock.ConvertToUserTime(dateTimeOffset); + convertedDateTimeOffset.Offset.ShouldBe(TimeSpan.Zero); + convertedDateTimeOffset.ShouldBe(dateTimeOffset); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTimeOffset = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified), TimeSpan.Zero); + var convertedDateTimeOffset = _clock.ConvertToUserTime(dateTimeOffset); + convertedDateTimeOffset.Offset.ShouldBe(TimeSpan.Zero); + convertedDateTimeOffset.ShouldBe(dateTimeOffset); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTimeOffset = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified), TimeSpan.FromHours(3)); + var convertedDateTimeOffset = _clock.ConvertToUserTime(dateTimeOffset); + convertedDateTimeOffset.Offset.ShouldBe(TimeSpan.FromHours(3)); + convertedDateTimeOffset.ShouldBe(dateTimeOffset); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTimeOffset = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified), TimeSpan.FromHours(8)); + var convertedDateTimeOffset = _clock.ConvertToUserTime(dateTimeOffset); + convertedDateTimeOffset.Offset.ShouldBe(TimeSpan.FromHours(8)); + convertedDateTimeOffset.ShouldBe(dateTimeOffset); + } + } + + [Fact] + public void ConvertFrom_Test() + { + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified); + var convertedDateTime = _clock.ConvertToUtc(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Unspecified); + convertedDateTime.ShouldBe(dateTime); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Local); + var convertedDateTime = _clock.ConvertToUtc(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Local); + convertedDateTime.ShouldBe(dateTime); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc); + var convertedDateTime = _clock.ConvertToUtc(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Utc); + convertedDateTime.ShouldBe(dateTime); + } + } +} diff --git a/framework/test/Volo.Abp.Timing.Tests/Volo/Abp/Timing/Clock_Utc_Tests.cs b/framework/test/Volo.Abp.Timing.Tests/Volo/Abp/Timing/Clock_Utc_Tests.cs new file mode 100644 index 0000000000..4ecbd0d4c6 --- /dev/null +++ b/framework/test/Volo.Abp.Timing.Tests/Volo/Abp/Timing/Clock_Utc_Tests.cs @@ -0,0 +1,132 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Volo.Abp.Testing; +using Xunit; + +namespace Volo.Abp.Timing; + +public class Clock_Utc_Tests : AbpIntegratedTest +{ + private readonly IClock _clock; + private readonly ICurrentTimezoneProvider _currentTimezoneProvider; + + public Clock_Utc_Tests() + { + _clock = GetRequiredService(); + _currentTimezoneProvider = GetRequiredService(); + } + + protected override void AfterAddApplication(IServiceCollection services) + { + services.Configure(options => + { + options.Kind = DateTimeKind.Utc; + }); + base.AfterAddApplication(services); + } + + [Fact] + public void ConvertTo_Test() + { + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc); + var convertedDateTime = _clock.ConvertToUserTime(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Unspecified); + convertedDateTime.ToString("O").ShouldBe("2025-03-01T08:30:00.0000000"); //Without Z + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + // ConvertTo will not convert the DateTimeKind.Local + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Local); + var convertedDateTime = _clock.ConvertToUserTime(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Local); + convertedDateTime.ToString("O").ShouldBe(dateTime.ToString("O")); + } + + using(_currentTimezoneProvider.Change(null)) + { + // ConvertTo will not convert if the timezone is not set + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Local); + var convertedDateTime = _clock.ConvertToUserTime(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Local); + convertedDateTime.ToString("O").ShouldBe(dateTime.ToString("O")); + } + } + + [Fact] + public void ConvertTo_DateTimeOffset_Test() + { + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTimeOffset = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc), TimeSpan.Zero); + var convertedDateTimeOffset = _clock.ConvertToUserTime(dateTimeOffset); + convertedDateTimeOffset.Offset.ShouldBe(TimeSpan.FromHours(3)); + convertedDateTimeOffset.ToString("O").ShouldBe("2025-03-01T08:30:00.0000000+03:00"); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTimeOffset = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified), TimeSpan.Zero); + var convertedDateTimeOffset = _clock.ConvertToUserTime(dateTimeOffset); + convertedDateTimeOffset.Offset.ShouldBe(TimeSpan.FromHours(3)); + convertedDateTimeOffset.ToString("O").ShouldBe("2025-03-01T08:30:00.0000000+03:00"); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTimeOffset = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified), TimeSpan.FromHours(3)); + var convertedDateTimeOffset = _clock.ConvertToUserTime(dateTimeOffset); + convertedDateTimeOffset.Offset.ShouldBe(TimeSpan.FromHours(3)); + convertedDateTimeOffset.ShouldBe(dateTimeOffset); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTimeOffset = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified), TimeSpan.FromHours(8)); + var convertedDateTimeOffset = _clock.ConvertToUserTime(dateTimeOffset); + convertedDateTimeOffset.Offset.ShouldBe(TimeSpan.FromHours(3)); + convertedDateTimeOffset.DateTime.ShouldBe(new DateTime(2025, 3, 1, 0, 30, 0, DateTimeKind.Unspecified)); + } + + using(_currentTimezoneProvider.Change(null)) + { + // ConvertTo will not convert if the timezone is not set + var dateTimeOffset = new DateTimeOffset(new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified), TimeSpan.FromHours(8)); + var convertedDateTimeOffset = _clock.ConvertToUserTime(dateTimeOffset); + convertedDateTimeOffset.Offset.ShouldBe(TimeSpan.FromHours(8)); + convertedDateTimeOffset.ShouldBe(dateTimeOffset); + } + } + + [Fact] + public void ConvertFrom_Test() + { + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Unspecified); + var convertedDateTime = _clock.ConvertToUtc(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Utc); + convertedDateTime.ToString("O").ShouldBe("2025-03-01T02:30:00.0000000Z"); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Local); + var convertedDateTime = _clock.ConvertToUtc(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Utc); + convertedDateTime.ToString("O").ShouldBe("2025-03-01T02:30:00.0000000Z"); + } + + using(_currentTimezoneProvider.Change("Europe/Istanbul")) + { + var dateTime = new DateTime(2025, 3, 1, 5, 30, 0, DateTimeKind.Utc); + var convertedDateTime = _clock.ConvertToUtc(dateTime); + convertedDateTime.Kind.ShouldBe(DateTimeKind.Utc); + convertedDateTime.ToString("O").ShouldBe("2025-03-01T05:30:00.0000000Z"); + } + } + +} diff --git a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Approve/Index.cshtml b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Approve/Index.cshtml index d15396f33d..788ae3f682 100644 --- a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Approve/Index.cshtml +++ b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Approve/Index.cshtml @@ -35,7 +35,7 @@ -
+
diff --git a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Approve/index.js b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Approve/index.js index f8aa2ba80d..587e7f77ec 100644 --- a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Approve/index.js +++ b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Approve/index.js @@ -6,15 +6,8 @@ moment()._locale.preparse = (string) => string; moment()._locale.postformat = (string) => string; - var getFormattedDate = function ($datePicker) { - if (!$datePicker.val()) { - return null; - } - var momentDate = moment($datePicker.val(), $datePicker.data('daterangepicker').locale.format); - return momentDate.isValid() ? momentDate.toISOString() : null; - }; - - $('.singledatepicker').daterangepicker({ + var singleDatePicker = $('#CmsKitCommentsApproveWrapper .singledatepicker'); + singleDatePicker.daterangepicker({ "singleDatePicker": true, "showDropdowns": true, "autoUpdateInput": false, @@ -23,22 +16,19 @@ "drops": "auto" }); - $('.singledatepicker').attr('autocomplete', 'off'); + singleDatePicker.attr('autocomplete', 'off'); - $('.singledatepicker').on('apply.daterangepicker', function (ev, picker) { + singleDatePicker.on('apply.daterangepicker', function (ev, picker) { $(this).val(picker.startDate.format('l')); }); var filterForm = $('#CmsKitCommentsFilterForm'); var getFilter = function () { - var filterObj = filterForm.serializeFormToObject(); - - filterObj.creationStartDate = getFormattedDate($('#CreationStartDate')); - filterObj.creationEndDate = getFormattedDate($('#CreationEndDate')); - filterObj.commentApproveState = "Waiting"; - - return filterObj; + filterForm.handleDatepicker('.singledatepicker'); + var formObject = filterForm.serializeFormToObject(); + formObject.commentApproveState = "Waiting"; + return formObject; }; var _dataTable = $('#CommentsTable').DataTable(abp.libs.datatables.normalizeConfiguration({ diff --git a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Details.cshtml b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Details.cshtml index a73475bac2..a9d064235f 100644 --- a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Details.cshtml +++ b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/Details.cshtml @@ -33,7 +33,7 @@ } -
+
diff --git a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/details.js b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/details.js index 2d007b0983..33f0b9211c 100644 --- a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/details.js +++ b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/details.js @@ -8,15 +8,12 @@ $(function (){ if (commentRequireApprovement) { $('#IsApprovedSelectInput').show(); } - - var getFormattedDate = function ($datePicker) { - return $datePicker.data('date'); - }; - + moment.localeData().preparse = (s)=>s; moment.localeData().postformat = (s)=>s; - - $('.singledatepicker').daterangepicker({ + + var singleDatePicker = $('#CmsKitCommentsDetailsWrapper .singledatepicker'); + singleDatePicker.daterangepicker({ "singleDatePicker": true, "showDropdowns": true, "autoUpdateInput": false, @@ -27,9 +24,9 @@ $(function (){ "maxYear": 2199, }); - $('.singledatepicker').attr('autocomplete', 'off'); + singleDatePicker.attr('autocomplete', 'off'); - $('.singledatepicker').on('apply.daterangepicker', function (ev, picker) { + singleDatePicker.on('apply.daterangepicker', function (ev, picker) { $(this).val(picker.startDate.format('l')); $(this).data('date', picker.startDate.locale('en').format('YYYY-MM-DD')); }); @@ -37,12 +34,9 @@ $(function (){ var filterForm = $('#CmsKitCommentsFilterForm'); var getFilter = function () { - var filterObj = filterForm.serializeFormToObject(); - - filterObj.creationStartDate = getFormattedDate($('#creationStartDate')); - filterObj.creationEndDate = getFormattedDate($('#creationEndDate')); - - return filterObj; + filterForm.handleDatepicker('.singledatepicker'); + var formObject = filterForm.serializeFormToObject(); + return formObject; }; var _dataTable = $('#CommentsTable').DataTable(abp.libs.datatables.normalizeConfiguration({ diff --git a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/index.js b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/index.js index be652ce552..ad0b8049f6 100644 --- a/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/index.js +++ b/modules/cms-kit/src/Volo.CmsKit.Admin.Web/Pages/CmsKit/Comments/index.js @@ -2,7 +2,6 @@ $(function () { var l = abp.localization.getResource("CmsKit"); var commentsService = volo.cmsKit.admin.comments.commentAdmin; - moment()._locale.preparse = (string) => string; moment()._locale.postformat = (string) => string; @@ -13,15 +12,8 @@ $(function () { $('#IsApprovedSelectInput').show(); } - var getFormattedDate = function ($datePicker) { - if (!$datePicker.val()) { - return null; - } - var momentDate = moment($datePicker.val(), $datePicker.data('daterangepicker').locale.format); - return momentDate.isValid() ? momentDate.toISOString() : null; - }; - - $('.singledatepicker').daterangepicker({ + var singleDatePicker = $('#CmsKitCommentsWrapper .singledatepicker'); + singleDatePicker.daterangepicker({ "singleDatePicker": true, "showDropdowns": true, "autoUpdateInput": false, @@ -30,21 +22,18 @@ $(function () { "drops": "auto" }); - $('.singledatepicker').attr('autocomplete', 'off'); + singleDatePicker.attr('autocomplete', 'off'); - $('.singledatepicker').on('apply.daterangepicker', function (ev, picker) { + singleDatePicker.on('apply.daterangepicker', function (ev, picker) { $(this).val(picker.startDate.format('l')); }); var filterForm = $('#CmsKitCommentsFilterForm'); var getFilter = function () { - var filterObj = filterForm.serializeFormToObject(); - - filterObj.creationStartDate = getFormattedDate($('#CreationStartDate')); - filterObj.creationEndDate = getFormattedDate($('#CreationEndDate')); - - return filterObj; + filterForm.handleDatepicker('.singledatepicker'); + var formObject = filterForm.serializeFormToObject(); + return formObject; }; var _dataTable = $('#CommentsTable').DataTable(abp.libs.datatables.normalizeConfiguration({ diff --git a/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Documents/index.js b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Documents/index.js index 395ef8587e..6dd0e1bde2 100644 --- a/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Documents/index.js +++ b/modules/docs/src/Volo.Docs.Admin.Web/Pages/Docs/Admin/Documents/index.js @@ -2,14 +2,11 @@ $(function () { var l = abp.localization.getResource('Docs'); var service = window.volo.docs.admin.documentsAdmin; - var getFormattedDate = function ($datePicker) { - return $datePicker.data('date'); - }; - moment.localeData().preparse = (s)=>s; moment.localeData().postformat = (s)=>s; - - $('.singledatepicker').daterangepicker({ + + var singleDatePicker = $('#DocumentsContainer .singledatepicker'); + singleDatePicker.daterangepicker({ "singleDatePicker": true, "showDropdowns": true, "autoUpdateInput": false, @@ -20,9 +17,9 @@ $(function () { "maxYear": 2199, }); - $('.singledatepicker').attr('autocomplete', 'off'); + singleDatePicker.attr('autocomplete', 'off'); - $('.singledatepicker').on('apply.daterangepicker', function (ev, picker) { + singleDatePicker.on('apply.daterangepicker', function (ev, picker) { $(this).val(picker.startDate.format('l')); $(this).data('date', picker.startDate.locale('en').format('YYYY-MM-DD')); }); @@ -130,23 +127,26 @@ $(function () { var getFilter = function () { + $('#DocumentsContainer').handleDatepicker('.singledatepicker'); + return { projectId: $('#ProjectId').val(), name: $('#Name').val(), version: $('#Version').val(), languageCode: $('#LanguageCode').val(), format: $('#Format').val(), - creationTimeMin: getFormattedDate($('#CreationTimeMin')), - creationTimeMax: getFormattedDate($('#CreationTimeMax')), - lastUpdatedTimeMin: getFormattedDate($('#LastUpdatedTimeMin')), - lastUpdatedTimeMax: getFormattedDate($('#LastUpdatedTimeMax')), - lastSignificantUpdateTimeMin: getFormattedDate($('#LastSignificantUpdateTimeMin')), - lastSignificantUpdateTimeMax: getFormattedDate($('#LastSignificantUpdateTimeMax')), - lastCachedTimeMin: getFormattedDate($('#LastCachedTimeMin')), - lastCachedTimeMax: getFormattedDate($('#LastCachedTimeMax')), + creationTimeMin: $('#DocumentsContainer').find('input[name="CreationTimeMin"'), + creationTimeMax: $('#DocumentsContainer').find('input[name="CreationTimeMax"'), + lastUpdatedTimeMin: $('#DocumentsContainer').find('input[name="LastUpdatedTimeMin"'), + lastUpdatedTimeMax: $('#DocumentsContainer').find('input[name="LastUpdatedTimeMax"'), + lastSignificantUpdateTimeMin: $('#DocumentsContainer').find('input[name="LastSignificantUpdateTimeMin"'), + lastSignificantUpdateTimeMax: $('#DocumentsContainer').find('input[name="LastSignificantUpdateTimeMax"'), + lastCachedTimeMin: $('#DocumentsContainer').find('input[name="LastCachedTimeMin"'), + lastCachedTimeMax: $('#DocumentsContainer').find('input[name="LastCachedTimeMax"'), }; }; + var parseDateToLocaleDateString = function (date) { var parsedDate = Date.parse(date); return new Date(parsedDate).toLocaleDateString( diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Application/Volo/Abp/SettingManagement/TimeZoneSettingsAppService.cs b/modules/setting-management/src/Volo.Abp.SettingManagement.Application/Volo/Abp/SettingManagement/TimeZoneSettingsAppService.cs index ee8580ac22..4aa5700d8e 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Application/Volo/Abp/SettingManagement/TimeZoneSettingsAppService.cs +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Application/Volo/Abp/SettingManagement/TimeZoneSettingsAppService.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; @@ -12,6 +13,8 @@ public class TimeZoneSettingsAppService : SettingManagementAppServiceBase, ITime protected ISettingManager SettingManager { get; } protected ITimezoneProvider TimezoneProvider { get; } + private const string UnspecifiedTimeZone = "Unspecified"; + public TimeZoneSettingsAppService(ISettingManager settingManager, ITimezoneProvider timezoneProvider) { SettingManager = settingManager; @@ -20,21 +23,36 @@ public class TimeZoneSettingsAppService : SettingManagementAppServiceBase, ITime public virtual async Task GetAsync() { - if (CurrentTenant.GetMultiTenancySide() == MultiTenancySides.Host) + var timezone = CurrentTenant.GetMultiTenancySide() == MultiTenancySides.Host + ? await SettingManager.GetOrNullGlobalAsync(TimingSettingNames.TimeZone) + : await SettingManager.GetOrNullForCurrentTenantAsync(TimingSettingNames.TimeZone); + + if (timezone.IsNullOrWhiteSpace()) { - return await SettingManager.GetOrNullGlobalAsync(TimingSettingNames.TimeZone); + timezone = UnspecifiedTimeZone; } - return await SettingManager.GetOrNullForCurrentTenantAsync(TimingSettingNames.TimeZone); + return timezone; } public virtual Task> GetTimezonesAsync() { - return Task.FromResult(TimeZoneHelper.GetTimezones(TimezoneProvider.GetWindowsTimezones())); + var timezones = TimeZoneHelper.GetTimezones(TimezoneProvider.GetIanaTimezones()); + timezones.Insert(0, new NameValue + { + Name = L["DefaultTimeZone"], + Value = UnspecifiedTimeZone + }); + return Task.FromResult(timezones); } public virtual async Task UpdateAsync(string timezone) { + if (timezone.Equals(UnspecifiedTimeZone, StringComparison.OrdinalIgnoreCase)) + { + timezone = null; + } + if (CurrentTenant.GetMultiTenancySide() == MultiTenancySides.Host) { await SettingManager.SetGlobalAsync(TimingSettingNames.TimeZone, timezone); diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ar.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ar.json index 1a0a2e218a..b5ef3930fb 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ar.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ar.json @@ -20,7 +20,8 @@ "Menu:Emailing": "إرسال بالبريد الإلكتروني", "Menu:TimeZone": "وحدة زمنية", "DisplayName:Timezone": "وحدة زمنية", - "TimezoneHelpText": "يُستخدم هذا الإعداد على مستوى التطبيق أو على أساس المستأجر.", + "TimezoneHelpText": "يُستخدم هذا الإعداد على مستوى التطبيق أو على أساس المستأجر. ستحاول الوحدة الزمنية الافتراضية استخدام وحدة زمنية المتصفح أو وحدة زمنية الخادم.", + "DefaultTimeZone": "الوحدة الزمنية الافتراضية", "SmtpHost": "مضيف", "SmtpPort": "ميناء", "SmtpUserName": "اسم المستخدم", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/cs.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/cs.json index 983c6718b9..0ad113214a 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/cs.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/cs.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Zasílání e-mailem", "Menu:TimeZone": "Časové Pásmo", "DisplayName:Timezone": "Časové pásmo", - "TimezoneHelpText": "Toto nastavení se používá pro celou aplikaci nebo pro klienty.", + "TimezoneHelpText": "Toto nastavení se používá pro celou aplikaci nebo pro klienty. Výchozí časové pásmo se pokusí použít časové pásmo prohlížeče nebo serveru.", + "DefaultTimeZone": "Výchozí časové pásmo", "SmtpHost": "Hostitel", "SmtpPort": "Přístav", "SmtpUserName": "Uživatelské jméno", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/de-DE.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/de-DE.json index 3f44913224..6e17d1c0dc 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/de-DE.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/de-DE.json @@ -20,7 +20,8 @@ "Menu:Emailing": "E-Mail", "Menu:TimeZone": "Zeitzone", "DisplayName:Timezone": "Zeitzone", - "TimezoneHelpText": "Diese Einstellung wird für die Anwendung oder den Mandanten verwendet.", + "TimezoneHelpText": "Diese Einstellung wird für die Anwendung oder den Mandanten verwendet. Die Standardzeitzone wird versuchen, die Zeitzone des Browsers oder des Servers zu verwenden.", + "DefaultTimeZone": "Standardzeitzone", "SmtpHost": "Host", "SmtpPort": "Port", "SmtpUserName": "Benutzername", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/de.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/de.json index c5efcb1718..a36781a157 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/de.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/de.json @@ -21,6 +21,8 @@ "Menu:TimeZone": "Zeitzone", "DisplayName:Timezone": "Zeitzone", "TimezoneHelpText": "Diese Einstellung wird anwendungsweit oder mandantenbasiert verwendet.", + "DefaultTimeZone": "Standardzeitzone", + "DefaultTimeZoneInfo": "Die Standardzeitzone wird versuchen, die Zeitzone des Browsers oder des Servers zu verwenden.", "SmtpHost": "Gastgeber", "SmtpPort": "Hafen", "SmtpUserName": "Nutzername", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/en.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/en.json index e7d221b4ef..1afbfa81cb 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/en.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/en.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Emailing", "Menu:TimeZone": "Time Zone", "DisplayName:Timezone": "Time zone", - "TimezoneHelpText": "This setting is used for application-wide or tenant-based.", + "TimezoneHelpText": "This setting is used for application-wide or tenant-based. The default timezone will try to use the browser's or the server's timezone.", + "DefaultTimeZone": "Default time zone", "SmtpHost": "Host", "SmtpPort": "Port", "SmtpUserName": "User name", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/es.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/es.json index 7d6bcd8236..202404917c 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/es.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/es.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Configuración", "Menu:TimeZone": "Zona Horaria", "DisplayName:Timezone": "Zona horaria", - "TimezoneHelpText": "Esta configuración se utiliza para toda la aplicación o basada en inquilinos.", + "TimezoneHelpText": "Esta configuración se utiliza para toda la aplicación o basada en inquilinos. La zona horaria predeterminada intentará usar la zona horaria del navegador o del servidor.", + "DefaultTimeZone": "Zona horaria predeterminada", "SmtpHost": "Host", "SmtpPort": "Puerto", "SmtpUserName": "Nombre de usuario", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/fi.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/fi.json index 312ecf608c..24ffd3fd5c 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/fi.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/fi.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Sähköpostiviestit", "Menu:TimeZone": "Aikavyöhyke", "DisplayName:Timezone": "Aikavyöhyke", - "TimezoneHelpText": "Tätä asetusta käytetään sovelluksenlaajuisesti tai vuokraajakohtaisesti.", + "TimezoneHelpText": "Tätä asetusta käytetään sovelluksenlaajuisesti tai vuokraajakohtaisesti. Oletusaikavyöhyke yrittää käyttää selaimen tai palvelimen aikavyöhykettä.", + "DefaultTimeZone": "Oletusaikavyöhyke", "SmtpHost": "Isäntä", "SmtpPort": "Portti", "SmtpUserName": "Käyttäjänimi", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/fr.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/fr.json index 3ec1a598c2..eb2c2f6620 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/fr.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/fr.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Envoi par e-mail", "Menu:TimeZone": "Fuseau Horaire", "DisplayName:Timezone": "Fuseau horaire", - "TimezoneHelpText": "Ce paramètre est utilisé à l’échelle de l’application ou basé sur le client.", + "TimezoneHelpText": "Ce paramètre est utilisé à l'échelle de l'application ou basé sur le client. Le fuseau horaire par défaut tentera d'utiliser le fuseau horaire du navigateur ou du serveur.", + "DefaultTimeZone": "Fuseau horaire par défaut", "SmtpHost": "Hôte", "SmtpPort": "Port", "SmtpUserName": "Nom d'utilisateur", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hi.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hi.json index 786616f901..ae23e424f2 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hi.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hi.json @@ -20,7 +20,8 @@ "Menu:Emailing": "ईमेल से भेजना", "Menu:TimeZone": "समय क्षेत्र", "DisplayName:Timezone": "समय क्षेत्र", - "TimezoneHelpText": "इस सेटिंग का उपयोग एप्लिकेशन-व्यापी या किरायेदार-आधारित के लिए किया जाता है।", + "TimezoneHelpText": "इस सेटिंग का उपयोग एप्लिकेशन-व्यापी या किरायेदार-आधारित के लिए किया जाता है। डिफ़ॉल्ट समय क्षेत्र ब्राउज़र या सर्वर के समय क्षेत्र का उपयोग करने का प्रयास करेगा।", + "DefaultTimeZone": "डिफ़ॉल्ट समय क्षेत्र", "SmtpHost": "मेज़बान", "SmtpPort": "बंदरगाह", "SmtpUserName": "उपयोगकर्ता नाम", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hr.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hr.json index acd0c132fa..02347180a6 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hr.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hr.json @@ -7,7 +7,7 @@ "Permission:Emailing": "Slanje e-poštom", "Permission:EmailingTest": "Test slanja e-pošte", "Permission:TimeZone": "Vremenska zona", - "SendTestEmail": "Po�alji probnu e-poštu", + "SendTestEmail": "Pošalji probnu e-poštu", "SenderEmailAddress": "Adresa e-pošte pošiljatelja", "TargetEmailAddress": "Ciljana adresa e-pošte", "Subject": "Predmet", @@ -21,6 +21,8 @@ "Menu:TimeZone": "Vremenska Zona", "DisplayName:Timezone": "Vremenska zona", "TimezoneHelpText": "Ova se postavka koristi za cijelu aplikaciju ili zakupce.", + "DefaultTimeZone": "Zadana vremenska zona", + "DefaultTimeZoneInfo": "Zadana vremenska zona pokušat će koristiti vremensku zonu preglednika ili poslužitelja.", "SmtpHost": "Domaćin", "SmtpPort": "Port", "SmtpUserName": "Korisničko ime", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hu.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hu.json index c47a813371..1273c17f50 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hu.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/hu.json @@ -20,7 +20,8 @@ "Menu:Emailing": "E-mailezés", "Menu:TimeZone": "Időzóna", "DisplayName:Timezone": "Időzóna", - "TimezoneHelpText": "Ez a beállítás az egész alkalmazásra vagy a bérlőre vonatkozik.", + "TimezoneHelpText": "Ez a beállítás az egész alkalmazásra vagy a bérlőre vonatkozik. Az alapértelmezett időzóna megpróbálja használni a böngésző vagy a szerver időzónáját.", + "DefaultTimeZone": "Alapértelmezett időzóna", "SmtpHost": "Házigazda", "SmtpPort": "Kikötő", "SmtpUserName": "Felhasználónév", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/is.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/is.json index f39b10f795..d6b1bd1f21 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/is.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/is.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Senda tölvupóst", "Menu:TimeZone": "Tímabelti", "DisplayName:Timezone": "Tímabelti", - "TimezoneHelpText": "Þessi stilling er notuð fyrir allt forrit eða leigjanda.", + "TimezoneHelpText": "Þessi stilling er notuð fyrir allt forrit eða leigjanda. Sjálfgefna tímabeltið mun reyna að nota tímabelti vafrans eða þjónsins.", + "DefaultTimeZone": "Sjálfgefitt tímabelti", "SmtpHost": "Smtp Host", "SmtpPort": "Port", "SmtpUserName": "Notanda nafn", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/it.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/it.json index 3de6657509..4f27439374 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/it.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/it.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Invio di e-mail", "Menu:TimeZone": "Fuso Orario", "DisplayName:Timezone": "Fuso orario", - "TimezoneHelpText": "Questa impostazione viene utilizzata per l'intera applicazione o in base al tenant.", + "TimezoneHelpText": "Questa impostazione viene utilizzata per l'intera applicazione o in base al tenant. Il fuso orario predefinito tenterà di utilizzare il fuso orario del browser o del server.", + "DefaultTimeZone": "Fuso orario predefinito", "SmtpHost": "Host", "SmtpPort": "Porta", "SmtpUserName": "Nome utente", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/nl.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/nl.json index a188146d0e..806b8006c3 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/nl.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/nl.json @@ -20,7 +20,8 @@ "Menu:Emailing": "E-mail", "Menu:TimeZone": "Tijdzone", "DisplayName:Timezone": "Tijdzone", - "TimezoneHelpText": "Deze instelling wordt gebruikt voor de hele toepassing of op tenantbasis.", + "TimezoneHelpText": "Deze instelling wordt gebruikt voor de hele toepassing of op tenantbasis. De standaardtijdzone zal proberen de tijdzone van de browser of de server te gebruiken.", + "DefaultTimeZone": "Standaardtijdzone", "SmtpHost": "Host", "SmtpPort": "Poort", "SmtpUserName": "Gebruikersnaam", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/pl-PL.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/pl-PL.json index a4bbd7238e..5b5c3c5c43 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/pl-PL.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/pl-PL.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Wysyłanie e-maili", "Menu:TimeZone": "Strefa Czasowa", "DisplayName:Timezone": "Strefa czasowa", - "TimezoneHelpText": "To ustawienie jest używane w przypadku całej aplikacji lub opartej na dzierżawie.", + "TimezoneHelpText": "To ustawienie jest używane w przypadku całej aplikacji lub opartej na dzierżawie. Domyślna strefa czasowa spróbuje użyć strefy czasowej przeglądarki lub serwera.", + "DefaultTimeZone": "Domyślna strefa czasowa", "SmtpHost": "Gospodarz", "SmtpPort": "Port", "SmtpUserName": "Nazwa użytkownika", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/pt-BR.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/pt-BR.json index c6c951c025..5baf3abff9 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/pt-BR.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/pt-BR.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Enviando por e-mail", "Menu:TimeZone": "Fuso Horário", "DisplayName:Timezone": "Fuso horário", - "TimezoneHelpText": "Essa configuração é usada para todo o aplicativo ou com base em locatário.", + "TimezoneHelpText": "Essa configuração é usada para todo o aplicativo ou com base em locatário. O fuso horário padrão tentará usar o fuso horário do navegador ou do servidor.", + "DefaultTimeZone": "Fuso horário padrão", "SmtpHost": "Hospedeiro", "SmtpPort": "Porta", "SmtpUserName": "Nome do usuário", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ro-RO.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ro-RO.json index 7e1eac80be..b14d3703dd 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ro-RO.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ro-RO.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Emailing", "Menu:TimeZone": "Fus Orar", "DisplayName:Timezone": "Fus orar", - "TimezoneHelpText": "Această setare este utilizată pentru aplicație sau pentru chiriași.", + "TimezoneHelpText": "Această setare este utilizată pentru aplicație sau pentru chiriași. Fusul orar implicit va încerca să folosească fusul orar al browserului sau al serverului.", + "DefaultTimeZone": "Fus orar implicit", "SmtpHost": "Host", "SmtpPort": "Port", "SmtpUserName": "Nume de utilizator", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ru.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ru.json index 9fde67ff61..788a4e23d1 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ru.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/ru.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Отправка по электронной почте", "Menu:TimeZone": "Часовой пояс", "DisplayName:Timezone": "Часовой пояс", - "TimezoneHelpText": "Этот параметр используется для всего приложения или на уровне клиента.", + "TimezoneHelpText": "Этот параметр используется для всего приложения или на уровне клиента. Часовой пояс по умолчанию попытается использовать часовой пояс браузера или сервера.", + "DefaultTimeZone": "Часовой пояс по умолчанию", "SmtpHost": "Хозяин", "SmtpPort": "Порт", "SmtpUserName": "Имя пользователя", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sk.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sk.json index e06c4d9d0a..13b8dce96b 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sk.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sk.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Posielanie emailov", "Menu:TimeZone": "Časové Pásmo", "DisplayName:Timezone": "Časové pásmo", - "TimezoneHelpText": "Toto nastavenie sa používa pre celú aplikáciu alebo pre nájomníkov.", + "TimezoneHelpText": "Toto nastavenie sa používa pre celú aplikáciu alebo pre nájomníkov. Predvolené časové pásmo sa pokúsi použiť časové pásmo prehliadača alebo servera.", + "DefaultTimeZone": "Predvolené časové pásmo", "SmtpHost": "Host", "SmtpPort": "Port", "SmtpUserName": "Meno používateľa", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sl.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sl.json index 509ce74e08..d79e045fd7 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sl.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sl.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Pošiljanje po e-pošti", "Menu:TimeZone": "Časovni Pas", "DisplayName:Timezone": "Časovni pas", - "TimezoneHelpText": "Ta nastavitev se uporablja za celotno aplikacijo ali za najemnika.", + "TimezoneHelpText": "Ta nastavitev se uporablja za celotno aplikacijo ali za najemnika. Privzeto časovno pas bo poskusilo uporabiti časovni pas brskalnika ali strežnika.", + "DefaultTimeZone": "Privzeto časovno pas", "SmtpHost": "Gostitelj", "SmtpPort": "pristanišče", "SmtpUserName": "Uporabniško ime", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sv.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sv.json index ad74a9c147..ebbdad2b32 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sv.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/sv.json @@ -19,7 +19,8 @@ "Menu:Emailing": "E-post", "Menu:TimeZone": "Tidszon", "DisplayName:Timezone": "Tidszon", - "TimezoneHelpText": "Denna inställning används för applikationsomfattande eller hyresgästbaserad.", + "TimezoneHelpText": "Denna inställning används för applikationsomfattande eller hyresgästbaserad. Standardtidszonen kommer att försöka använda webbläsarens eller serverns tidszon.", + "DefaultTimeZone": "Standardtidszon", "SmtpHost": "Värd", "SmtpPort": "Port", "SmtpUserName": "Användarens namn", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/tr.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/tr.json index aab8928026..ad2cbbb8ef 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/tr.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/tr.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Email", "Menu:TimeZone": "Zaman Dilimi", "DisplayName:Timezone": "Zaman dilimi", - "TimezoneHelpText": "Bu ayar uygulama genelinde veya müşteri tabanlı olarak kullanılır.", + "TimezoneHelpText": "Bu ayar uygulama genelinde veya müşteri tabanlı olarak kullanılır. Varsayılan saat dilimi, tarayıcının veya sunucunun saat dilimini kullanmaya çalışacaktır.", + "DefaultTimeZone": "Varsayılan saat dilimi", "SmtpHost": "Sunucu", "SmtpPort": "Port", "SmtpUserName": "Kullanıcı adı", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/vi.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/vi.json index 94acb63a71..200c437d44 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/vi.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/vi.json @@ -20,7 +20,8 @@ "Menu:Emailing": "Gửi email", "Menu:TimeZone": "Múi Giờ", "DisplayName:Timezone": "Múi giờ", - "TimezoneHelpText": "Cài đặt này được sử dụng cho toàn bộ ứng dụng hoặc dựa trên đối tượng thuê.", + "TimezoneHelpText": "Cài đặt này được sử dụng cho toàn bộ ứng dụng hoặc dựa trên đối tượng thuê. Múi giờ mặc định sẽ cố gắng sử dụng múi giờ của trình duyệt hoặc máy chủ.", + "DefaultTimeZone": "Múi giờ mặc định", "SmtpHost": "Tổ chức", "SmtpPort": "Hải cảng", "SmtpUserName": "Tên tài khoản", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/zh-Hans.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/zh-Hans.json index 339f14e292..76e9cd3526 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/zh-Hans.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/zh-Hans.json @@ -20,7 +20,8 @@ "Menu:Emailing": "邮件", "Menu:TimeZone": "时区", "DisplayName:Timezone": "时区", - "TimezoneHelpText": "此设置用于应用程序范围或基于租户。", + "TimezoneHelpText": "此设置用于应用程序范围或基于租户。默认时区将尝试使用浏览器的时区或服务器的时区。", + "DefaultTimeZone": "默认时区", "SmtpHost": "主机", "SmtpPort": "端口", "SmtpUserName": "用户名", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/zh-Hant.json b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/zh-Hant.json index e3a06511c2..8ce6679659 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/zh-Hant.json +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Domain.Shared/Volo/Abp/SettingManagement/Localization/Resources/AbpSettingManagement/zh-Hant.json @@ -20,7 +20,8 @@ "Menu:Emailing": "信箱", "Menu:TimeZone": "時區", "DisplayName:Timezone": "時區", - "TimezoneHelpText": "此設置用於應用程序範圍或基於租戶。", + "TimezoneHelpText": "此設置用於應用程序範圍或基於租戶。預設時區將嘗試使用瀏覽器的時區或伺服器的時區。", + "DefaultTimeZone": "預設時區", "SmtpHost": "主機", "SmtpPort": "Port", "SmtpUserName": "帳號", diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.cshtml b/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.cshtml index c146118cb3..11d9af9637 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.cshtml +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.cshtml @@ -1,18 +1,18 @@ @using Microsoft.AspNetCore.Mvc.Localization @using Volo.Abp.SettingManagement.Localization @inject IHtmlLocalizer L -@model Volo.Abp.SettingManagement.Web.Pages.SettingManagement.Components.TimeZoneSettingGroup.TimeZoneSettingGroupViewComponent.UpdateTimezoneSettingsViewModel -
- + +
+
@L["TimezoneHelpText"].Value
- + @L["Save"]
diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.js b/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.js index d6e720dbe3..aebbe66352 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.js +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.js @@ -3,13 +3,28 @@ var l = abp.localization.getResource('AbpSettingManagement'); + var select2 = null; + volo.abp.settingManagement.timeZoneSettings.getTimezones().then(function (result) { + var data = $.map(result, function (obj) { + obj.id = obj.value; + obj.text = obj.name; + return obj; + }); + + select2 = $("#timezone-select").select2({ + data: data + }); + + volo.abp.settingManagement.timeZoneSettings.get().then(function (result) { + select2.val(result).trigger("change"); + }); + }); + $("#TimeZoneSettingsForm").on('submit', function (event) { event.preventDefault(); - - volo.abp.settingManagement.timeZoneSettings.update($("#Timezone").val()).then(function (result) { + volo.abp.settingManagement.timeZoneSettings.update($("#timezone-select").val()).then(function (result) { $(document).trigger("AbpSettingSaved"); }); - }); }); })(jQuery); diff --git a/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/TimeZoneSettingGroupViewComponent.cs b/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/TimeZoneSettingGroupViewComponent.cs index eaf24ab2f2..9c22152a6f 100644 --- a/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/TimeZoneSettingGroupViewComponent.cs +++ b/modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/TimeZoneSettingGroupViewComponent.cs @@ -1,42 +1,18 @@ -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Threading.Tasks; +using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Rendering; using Volo.Abp.AspNetCore.Mvc; -using Volo.Abp.Auditing; -using Volo.Abp.Timing.Localization.Resources.AbpTiming; namespace Volo.Abp.SettingManagement.Web.Pages.SettingManagement.Components.TimeZoneSettingGroup; public class TimeZoneSettingGroupViewComponent : AbpViewComponent { - protected ITimeZoneSettingsAppService TimeZoneSettingsAppService { get; } - public TimeZoneSettingGroupViewComponent(ITimeZoneSettingsAppService timeZoneSettingsAppService) { ObjectMapperContext = typeof(AbpSettingManagementWebModule); - TimeZoneSettingsAppService = timeZoneSettingsAppService; } public virtual async Task InvokeAsync() { - var timezone = await TimeZoneSettingsAppService.GetAsync(); - var timezones = await TimeZoneSettingsAppService.GetTimezonesAsync(); - var model = new UpdateTimezoneSettingsViewModel() - { - Timezone = timezone, - TimeZoneItems = new List() - }; - model.TimeZoneItems.AddRange(timezones.Select(x => new SelectListItem(x.Name, x.Value)).ToList()); - return View("~/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.cshtml", model); - } - - public class UpdateTimezoneSettingsViewModel - { - public string Timezone { get; set; } - - public List TimeZoneItems { get; set; } + return View("~/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.cshtml"); } } diff --git a/npm/packs/core/src/abp.js b/npm/packs/core/src/abp.js index 05c9f3bbe5..8d11ad1fec 100644 --- a/npm/packs/core/src/abp.js +++ b/npm/packs/core/src/abp.js @@ -81,7 +81,7 @@ var abp = abp || {}; if (resource) { return resource; } - + var legacySource = abp.localization.values[resourceName]; if (legacySource) { return { @@ -89,11 +89,11 @@ var abp = abp || {}; baseResources: [] }; } - - abp.log.warn('Could not find localization source: ' + resourceName); + + abp.log.warn('Could not find localization source: ' + resourceName); return null; }; - + abp.localization.internal.localize = function (key, sourceName) { var resource = abp.localization.internal.getResource(sourceName); if (!resource){ @@ -104,7 +104,7 @@ var abp = abp || {}; } var value = resource.texts[key]; - if (value === undefined) { + if (value === undefined) { for (var i = 0; i < resource.baseResources.length; i++){ var basedArguments = Array.prototype.slice.call(arguments, 0); basedArguments[1] = resource.baseResources[i]; @@ -114,7 +114,7 @@ var abp = abp || {}; return result; } } - + return { value: key, found: false @@ -135,7 +135,7 @@ var abp = abp || {}; if (sourceName === '_') { //A convention to suppress the localization return key; } - + if (sourceName) { return abp.localization.internal.localize.apply(this, arguments).value; } @@ -750,7 +750,11 @@ var abp = abp || {}; abp.clock.supportsMultipleTimezone = function () { return abp.clock.kind === 'Utc'; - }; + } + + abp.clock.timeZone = function () { + return abp.setting.get('Abp.Timing.TimeZone') || abp.clock.browserTimeZone(); + } // Normalize Date object or date string to standard string format that will be sent to server abp.clock.normalizeToString = function (date) { @@ -763,32 +767,42 @@ var abp = abp || {}; return date; } - if (abp.clock.kind === 'Utc') { - return dateObj.toISOString(); - } - function padZero(num) { return num < 10 ? '0' + num : num; } - function padMilliseconds(num) { - if (num < 10) return '00' + num; - if (num < 100) return '0' + num; - return num; + var addZulu = false; + if (abp.clock.supportsMultipleTimezone()) { + var timeZone = abp.clock.timeZone(); + var now = new Date(); + var formattedDate = now.toLocaleString('en-US', { timeZone: timeZone, timeZoneName: 'longOffset' }); + var match = formattedDate.match(/GMT([+-]\d+)/); + var targetOffsetHours = match ? parseInt(match[1], 10) : 0; + var dateObj = new Date(dateObj.getTime() - (targetOffsetHours * 60 * 60 * 1000)); + addZulu = true; } - - // yyyy-MM-ddTHH:mm:ss.SSS + + // yyyy-MM-DDTHH:mm:ss return dateObj.getFullYear() + '-' + - padZero(dateObj.getMonth() + 1) + '-' + - padZero(dateObj.getDate()) + 'T' + - padZero(dateObj.getHours()) + ':' + - padZero(dateObj.getMinutes()) + ':' + - padZero(dateObj.getSeconds()) + '.' + - padMilliseconds(dateObj.getMilliseconds()); + padZero(dateObj.getMonth() + 1) + '-' + + padZero(dateObj.getDate()) + 'T' + + padZero(dateObj.getHours()) + ':' + + padZero(dateObj.getMinutes()) + ':' + + padZero(dateObj.getSeconds()) + (addZulu ? 'Z' : ''); + }; + + // Default options for toLocaleString + abp.clock.toLocaleStringOptions = abp.clock.toLocaleStringOptions || { + "year": "numeric", + "month": "long", + "day": "numeric", + "hour": "numeric", + "minute": "numeric", + "second": "numeric" }; // Normalize date string to locale date string that will be displayed to user - abp.clock.normalizeToLocaleString = function (dateString) { + abp.clock.normalizeToLocaleString = function (dateString, options) { if (!dateString) { return dateString; } @@ -797,11 +811,36 @@ var abp = abp || {}; if (isNaN(date)) { return dateString; } - - //TODO: Get timezone setting and pass it to toLocaleString - return date.toLocaleString(); + + var culture = abp.localization.currentCulture.cultureName; + options = options || abp.clock.toLocaleStringOptions; + if (abp.clock.supportsMultipleTimezone()) { + var timezone = abp.clock.timeZone(); + if (timezone) { + return date.toLocaleString(culture, Object.assign({}, options, { timeZone: timezone })); + } + } + return date.toLocaleString(culture, options); } + abp.clock.browserTimeZone = function () { + return Intl.DateTimeFormat().resolvedOptions().timeZone; + } + + abp.clock.trySetBrowserTimeZoneToCookie = true; + + abp.clock.setBrowserTimeZoneToCookie = function () { + if (!abp.clock.trySetBrowserTimeZoneToCookie || !abp.clock.supportsMultipleTimezone() || abp.currentUser.isAuthenticated) { + return; + } + + abp.utils.setCookieValue('__timezone', abp.clock.browserTimeZone(), new Date(new Date().setFullYear(new Date().getFullYear() + 1)), '/'); + } + + abp.event.on('abp.configurationInitialized', function () { + abp.clock.setBrowserTimeZoneToCookie(); + }); + /* FEATURES *************************************************/ abp.features = abp.features || {}; diff --git a/npm/packs/luxon/src/abp.luxon.js b/npm/packs/luxon/src/abp.luxon.js index b04de7cadf..40b3f965b8 100644 --- a/npm/packs/luxon/src/abp.luxon.js +++ b/npm/packs/luxon/src/abp.luxon.js @@ -32,7 +32,7 @@ var abp = abp || {}; .fromFormat( getObjectValue(form, field), abp.localization.currentCulture.dateTimeFormat.shortDatePattern, - {locale: abp.localization.currentCulture.cultureName} + { locale: abp.localization.currentCulture.cultureName } ); if (!dateTime.invalid) { @@ -43,4 +43,60 @@ var abp = abp || {}; return form; } + // Normalize Date object or date string to standard string format that will be sent to server + abp.clock.normalizeToString = function (date) { + if (!date) { + return date; + } + + var dateObj = date instanceof Date ? date : new Date(date); + if (isNaN(dateObj)) { + return date; + } + + var timeZone = abp.clock.timeZone(); + if (abp.clock.supportsMultipleTimezone() && timeZone) { + return luxon.DateTime.fromObject({ + year: dateObj.getFullYear(), + month: dateObj.getMonth() + 1, + day: dateObj.getDate(), + hour: dateObj.getHours(), + minute: dateObj.getMinutes(), + second: dateObj.getSeconds() + }, { zone: timeZone }).setZone("utc").toISO(); + } else { + return luxon.DateTime.fromJSDate(dateObj).toFormat("yyyy-MM-dd'T'HH:mm:ss"); + } + }; + + // Normalize date string to locale date string that will be displayed to user + abp.clock.normalizeToLocaleString = function (dateString, options) { + if (!dateString) { + return dateString; + } + + var date = new Date(dateString); + if (isNaN(date)) { + return dateString; + } + + options = options || abp.clock.toLocaleStringOptions; + if (abp.clock.supportsMultipleTimezone()) { + var timezone = abp.clock.timeZone(); + if (timezone) { + return luxon.DateTime.fromJSDate(date) + .setZone(timezone) + .setLocale(abp.localization.currentCulture.cultureName) + .toLocaleString(options); + } + } + + return luxon.DateTime.fromJSDate(date) + .setLocale(abp.localization.currentCulture.cultureName) + .toLocaleString(options); + } + + abp.clock.browserTimeZone = function () { + return luxon.DateTime.local().zoneName; + } })(jQuery);