From e0dabdf205a52f91828caf9ecec5705eb1541b56 Mon Sep 17 00:00:00 2001 From: Guy Boicey Date: Tue, 28 Feb 2023 13:53:32 -0800 Subject: [PATCH 1/3] Removed items not related to project --- BlazorBrowserTime.sln | 10 +--- .../Data/WeatherForecast.cs | 15 ----- .../Data/WeatherForecastService.cs | 25 -------- BlazorBrowserTimeDotNet5/Pages/Counter.razor | 23 ------- .../Pages/FetchData.razor | 46 -------------- BlazorBrowserTimeDotNet5/Startup.cs | 60 ------------------- .../wwwroot/sample-data/weather.json | 27 --------- 7 files changed, 2 insertions(+), 204 deletions(-) delete mode 100644 BlazorBrowserTimeDotNet5/Data/WeatherForecast.cs delete mode 100644 BlazorBrowserTimeDotNet5/Data/WeatherForecastService.cs delete mode 100644 BlazorBrowserTimeDotNet5/Pages/Counter.razor delete mode 100644 BlazorBrowserTimeDotNet5/Pages/FetchData.razor delete mode 100644 BlazorBrowserTimeDotNet5/Startup.cs delete mode 100644 BlazorWebAssemblyTimeTest/wwwroot/sample-data/weather.json diff --git a/BlazorBrowserTime.sln b/BlazorBrowserTime.sln index e132635..556939d 100644 --- a/BlazorBrowserTime.sln +++ b/BlazorBrowserTime.sln @@ -1,10 +1,8 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.31205.134 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.33414.496 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorBrowserTime", "BlazorBrowserTime\BlazorBrowserTime.csproj", "{2CFD970B-F965-4492-90FE-1597F27C6BDF}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorTime", "BrowserTime\BlazorTime.csproj", "{BFE118C2-EC21-4586-9538-755B4CDFB070}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorBrowserTimeDotNet5", "BlazorBrowserTimeDotNet5\BlazorBrowserTimeDotNet5.csproj", "{91FF3C72-EC75-4D90-9554-F744BB08EE55}" @@ -17,10 +15,6 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2CFD970B-F965-4492-90FE-1597F27C6BDF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2CFD970B-F965-4492-90FE-1597F27C6BDF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2CFD970B-F965-4492-90FE-1597F27C6BDF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2CFD970B-F965-4492-90FE-1597F27C6BDF}.Release|Any CPU.Build.0 = Release|Any CPU {BFE118C2-EC21-4586-9538-755B4CDFB070}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BFE118C2-EC21-4586-9538-755B4CDFB070}.Debug|Any CPU.Build.0 = Debug|Any CPU {BFE118C2-EC21-4586-9538-755B4CDFB070}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/BlazorBrowserTimeDotNet5/Data/WeatherForecast.cs b/BlazorBrowserTimeDotNet5/Data/WeatherForecast.cs deleted file mode 100644 index dd84f80..0000000 --- a/BlazorBrowserTimeDotNet5/Data/WeatherForecast.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace BlazorBrowserTimeDotNet5.Data -{ - public class WeatherForecast - { - public DateTime Date { get; set; } - - public int TemperatureC { get; set; } - - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - - public string Summary { get; set; } - } -} diff --git a/BlazorBrowserTimeDotNet5/Data/WeatherForecastService.cs b/BlazorBrowserTimeDotNet5/Data/WeatherForecastService.cs deleted file mode 100644 index ec72146..0000000 --- a/BlazorBrowserTimeDotNet5/Data/WeatherForecastService.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; - -namespace BlazorBrowserTimeDotNet5.Data -{ - public class WeatherForecastService - { - private static readonly string[] Summaries = new[] - { - "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" - }; - - public Task GetForecastAsync(DateTime startDate) - { - var rng = new Random(); - return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = startDate.AddDays(index), - TemperatureC = rng.Next(-20, 55), - Summary = Summaries[rng.Next(Summaries.Length)] - }).ToArray()); - } - } -} diff --git a/BlazorBrowserTimeDotNet5/Pages/Counter.razor b/BlazorBrowserTimeDotNet5/Pages/Counter.razor deleted file mode 100644 index 4872c94..0000000 --- a/BlazorBrowserTimeDotNet5/Pages/Counter.razor +++ /dev/null @@ -1,23 +0,0 @@ -@page "/counter" - -

Counter 2

- -

Current count: @currentCount

- - - -
-

Above

- - -

Below

-
- -@code { - private int currentCount = 0; - private DateTime currentTime = DateTime.UtcNow; - private void IncrementCount() - { - currentCount++; - } -} diff --git a/BlazorBrowserTimeDotNet5/Pages/FetchData.razor b/BlazorBrowserTimeDotNet5/Pages/FetchData.razor deleted file mode 100644 index 2f322c5..0000000 --- a/BlazorBrowserTimeDotNet5/Pages/FetchData.razor +++ /dev/null @@ -1,46 +0,0 @@ -@page "/fetchdata" - -@using BlazorBrowserTimeDotNet5.Data -@inject WeatherForecastService ForecastService - -

Weather forecast

- -

This component demonstrates fetching data from a service.

- -@if (forecasts == null) -{ -

Loading...

-} -else -{ - - - - - - - - - - - @foreach (var forecast in forecasts) - { - - - - - - - } - -
DateTemp. (C)Temp. (F)Summary
@forecast.Date.ToShortDateString()@forecast.TemperatureC@forecast.TemperatureF@forecast.Summary
-} - -@code { - private WeatherForecast[] forecasts; - - protected override async Task OnInitializedAsync() - { - forecasts = await ForecastService.GetForecastAsync(DateTime.Now); - } -} diff --git a/BlazorBrowserTimeDotNet5/Startup.cs b/BlazorBrowserTimeDotNet5/Startup.cs deleted file mode 100644 index 6b0bcd4..0000000 --- a/BlazorBrowserTimeDotNet5/Startup.cs +++ /dev/null @@ -1,60 +0,0 @@ -using BlazorBrowserTimeDotNet5.Data; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.HttpsPolicy; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace BlazorBrowserTimeDotNet5 -{ - public class Startup - { - public Startup(IConfiguration configuration) - { - Configuration = configuration; - } - - public IConfiguration Configuration { get; } - - // This method gets called by the runtime. Use this method to add services to the container. - // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 - public void ConfigureServices(IServiceCollection services) - { - services.AddRazorPages(); - services.AddServerSideBlazor(); - services.AddSingleton(); - } - - // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IWebHostEnvironment env) - { - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } - else - { - app.UseExceptionHandler("/Error"); - // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. - app.UseHsts(); - } - - app.UseHttpsRedirection(); - app.UseStaticFiles(); - - app.UseRouting(); - - app.UseEndpoints(endpoints => - { - endpoints.MapBlazorHub(); - endpoints.MapFallbackToPage("/_Host"); - }); - } - } -} diff --git a/BlazorWebAssemblyTimeTest/wwwroot/sample-data/weather.json b/BlazorWebAssemblyTimeTest/wwwroot/sample-data/weather.json deleted file mode 100644 index 06463c0..0000000 --- a/BlazorWebAssemblyTimeTest/wwwroot/sample-data/weather.json +++ /dev/null @@ -1,27 +0,0 @@ -[ - { - "date": "2018-05-06", - "temperatureC": 1, - "summary": "Freezing" - }, - { - "date": "2018-05-07", - "temperatureC": 14, - "summary": "Bracing" - }, - { - "date": "2018-05-08", - "temperatureC": -13, - "summary": "Freezing" - }, - { - "date": "2018-05-09", - "temperatureC": -16, - "summary": "Balmy" - }, - { - "date": "2018-05-10", - "temperatureC": -2, - "summary": "Chilly" - } -] From ae2516039b32a5d7d93956d5004ea970fec7bba0 Mon Sep 17 00:00:00 2001 From: Guy Boicey Date: Tue, 28 Feb 2023 13:54:52 -0800 Subject: [PATCH 2/3] Upgrade to .NET 6.0 --- .../BlazorBrowserTimeDotNet5.csproj | 2 +- BlazorBrowserTimeDotNet5/Pages/Index.razor | 64 +++++++++++++++- BlazorBrowserTimeDotNet5/Pages/NextPage.razor | 73 +++++++++++++++++++ BlazorBrowserTimeDotNet5/Pages/_Host.cshtml | 5 -- BlazorBrowserTimeDotNet5/Program.cs | 48 ++++++------ .../Shared/MainLayout.razor | 17 +---- .../BlazorWebAssemblyTimeTest.csproj | 8 +- BlazorWebAssemblyTimeTest/Pages/Index.razor | 2 +- BlazorWebAssemblyTimeTest/Program.cs | 25 ++----- 9 files changed, 176 insertions(+), 68 deletions(-) create mode 100644 BlazorBrowserTimeDotNet5/Pages/NextPage.razor diff --git a/BlazorBrowserTimeDotNet5/BlazorBrowserTimeDotNet5.csproj b/BlazorBrowserTimeDotNet5/BlazorBrowserTimeDotNet5.csproj index 66b53a7..e4f4018 100644 --- a/BlazorBrowserTimeDotNet5/BlazorBrowserTimeDotNet5.csproj +++ b/BlazorBrowserTimeDotNet5/BlazorBrowserTimeDotNet5.csproj @@ -1,7 +1,7 @@ - net5.0 + net6.0 diff --git a/BlazorBrowserTimeDotNet5/Pages/Index.razor b/BlazorBrowserTimeDotNet5/Pages/Index.razor index e54d914..05dfcf1 100644 --- a/BlazorBrowserTimeDotNet5/Pages/Index.razor +++ b/BlazorBrowserTimeDotNet5/Pages/Index.razor @@ -1,7 +1,65 @@ @page "/" -

Hello, world!

+
+

⌚ Time

+
-Welcome to your new app. +
+
+

+ Change Page +

- +

+ BROWSER DATE: +

+

+ BROWSER TIME: +

+

+ BROWSER DEFAULT: +

+ +

+ BROWSER DEFAULT (sent server time): +

+ +

+ UTC (RENDERED IN BROWSER): +

+ +

+ UTC (RENDERED IN BROWSER): +

+ +

@GuidString

+ +
+ + + +
+
+ +@code { + private DateTime testUtcTime = DateTime.UtcNow; + private DateTime testServerTime = DateTime.Now; + private DateTime testOneUtcTime = DateTime.UtcNow; + private String GuidString = Guid.NewGuid().ToString(); + + private void Update() + { + testUtcTime = DateTime.UtcNow; + testServerTime = DateTime.Now; + } + + private void UpdateOneTime() + { + testOneUtcTime = DateTime.UtcNow; + } + + private void UpdateNotTime() + { + GuidString = Guid.NewGuid().ToString(); + } +} diff --git a/BlazorBrowserTimeDotNet5/Pages/NextPage.razor b/BlazorBrowserTimeDotNet5/Pages/NextPage.razor new file mode 100644 index 0000000..d44c958 --- /dev/null +++ b/BlazorBrowserTimeDotNet5/Pages/NextPage.razor @@ -0,0 +1,73 @@ +@page "/next" + +
+

📃 Page Change

+
+ +
+
+

+ Back +

+
+
+ +
+
+

+ Change Page +

+ +

+ BROWSER DATE: +

+

+ BROWSER TIME: +

+

+ BROWSER DEFAULT: +

+ +

+ BROWSER DEFAULT (sent server time): +

+ +

+ UTC (RENDERED IN BROWSER): +

+ +

+ UTC (RENDERED IN BROWSER): +

+ +

@GuidString

+ +
+ + + +
+
+ +@code { + private DateTime testUtcTime = DateTime.UtcNow; + private DateTime testServerTime = DateTime.Now; + private DateTime testOneUtcTime = DateTime.UtcNow; + private String GuidString = Guid.NewGuid().ToString(); + + private void Update() + { + testUtcTime = DateTime.UtcNow; + testServerTime = DateTime.Now; + } + + private void UpdateOneTime() + { + testOneUtcTime = DateTime.UtcNow; + } + + private void UpdateNotTime() + { + GuidString = Guid.NewGuid().ToString(); + } +} diff --git a/BlazorBrowserTimeDotNet5/Pages/_Host.cshtml b/BlazorBrowserTimeDotNet5/Pages/_Host.cshtml index bdeec9a..2288afa 100644 --- a/BlazorBrowserTimeDotNet5/Pages/_Host.cshtml +++ b/BlazorBrowserTimeDotNet5/Pages/_Host.cshtml @@ -32,10 +32,5 @@ - diff --git a/BlazorBrowserTimeDotNet5/Program.cs b/BlazorBrowserTimeDotNet5/Program.cs index c42308c..02323a4 100644 --- a/BlazorBrowserTimeDotNet5/Program.cs +++ b/BlazorBrowserTimeDotNet5/Program.cs @@ -1,26 +1,32 @@ +using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Logging; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -namespace BlazorBrowserTimeDotNet5 + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddRazorPages(); +builder.Services.AddServerSideBlazor(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (!app.Environment.IsDevelopment()) { - public class Program - { - public static void Main(string[] args) - { - CreateHostBuilder(args).Build().Run(); - } - - public static IHostBuilder CreateHostBuilder(string[] args) => - Host.CreateDefaultBuilder(args) - .ConfigureWebHostDefaults(webBuilder => - { - webBuilder.UseStartup(); - }); - } + app.UseExceptionHandler("/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); } + +app.UseHttpsRedirection(); + +app.UseStaticFiles(); + +app.UseRouting(); + +app.MapBlazorHub(); +app.MapFallbackToPage("/_Host"); + +app.Run(); diff --git a/BlazorBrowserTimeDotNet5/Shared/MainLayout.razor b/BlazorBrowserTimeDotNet5/Shared/MainLayout.razor index 2281c4f..aa4a3d3 100644 --- a/BlazorBrowserTimeDotNet5/Shared/MainLayout.razor +++ b/BlazorBrowserTimeDotNet5/Shared/MainLayout.razor @@ -1,17 +1,4 @@ @inherits LayoutComponentBase - -
- - -
-
- About -
- -
- @Body -
-
+
+ @Body
diff --git a/BlazorWebAssemblyTimeTest/BlazorWebAssemblyTimeTest.csproj b/BlazorWebAssemblyTimeTest/BlazorWebAssemblyTimeTest.csproj index d1d8c23..ae136d3 100644 --- a/BlazorWebAssemblyTimeTest/BlazorWebAssemblyTimeTest.csproj +++ b/BlazorWebAssemblyTimeTest/BlazorWebAssemblyTimeTest.csproj @@ -1,13 +1,13 @@ - net5.0 + net6.0 - - - + + + diff --git a/BlazorWebAssemblyTimeTest/Pages/Index.razor b/BlazorWebAssemblyTimeTest/Pages/Index.razor index 22ea3a2..71edac4 100644 --- a/BlazorWebAssemblyTimeTest/Pages/Index.razor +++ b/BlazorWebAssemblyTimeTest/Pages/Index.razor @@ -3,7 +3,7 @@

Hello, world 4!

- Current time: + Current time:

diff --git a/BlazorWebAssemblyTimeTest/Program.cs b/BlazorWebAssemblyTimeTest/Program.cs index 15ed632..d6cfdf2 100644 --- a/BlazorWebAssemblyTimeTest/Program.cs +++ b/BlazorWebAssemblyTimeTest/Program.cs @@ -1,25 +1,14 @@ +using BlazorWebAssemblyTimeTest; +using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; using System; -using System.Collections.Generic; using System.Net.Http; -using System.Text; -using System.Threading.Tasks; -namespace BlazorWebAssemblyTimeTest -{ - public class Program - { - public static async Task Main(string[] args) - { - var builder = WebAssemblyHostBuilder.CreateDefault(args); - builder.RootComponents.Add("#app"); +var builder = WebAssemblyHostBuilder.CreateDefault(args); +builder.RootComponents.Add("#app"); +builder.RootComponents.Add("head::after"); - builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); +builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); - await builder.Build().RunAsync(); - } - } -} +await builder.Build().RunAsync(); \ No newline at end of file From a00d2aedb6b9332bb887af2850efab8a1bd1ab7c Mon Sep 17 00:00:00 2001 From: Guy Boicey Date: Tue, 28 Feb 2023 14:07:59 -0800 Subject: [PATCH 3/3] Changed to use .NET DateTime formating and other things Create .NET methods to format date/time. Calling those functions from JavaScript. This replaces node-dateformat functions. Makes formatting exactly the same as .NET instead of a JavaScript library. 1. Change HTML to be semantic with HTML5 using data- and span instead of custom tags and attributes 2. Used OnAfterRenderAsync with a flag to indicate the component was created instead of using HTML observations --- BrowserTime/.editorconfig | 6 +++ BrowserTime/BlazorTime.csproj | 7 ++- BrowserTime/ToLocal.razor | 72 +++++++++++++++++++++++++------ BrowserTime/wwwroot/blazorTime.js | 52 +++++++++------------- 4 files changed, 90 insertions(+), 47 deletions(-) create mode 100644 BrowserTime/.editorconfig diff --git a/BrowserTime/.editorconfig b/BrowserTime/.editorconfig new file mode 100644 index 0000000..0696893 --- /dev/null +++ b/BrowserTime/.editorconfig @@ -0,0 +1,6 @@ +root = true +[*] +indent_style = space + +[*.{cs,razor,js}] +indent_size = 2 \ No newline at end of file diff --git a/BrowserTime/BlazorTime.csproj b/BrowserTime/BlazorTime.csproj index 28728e8..9882dd1 100644 --- a/BrowserTime/BlazorTime.csproj +++ b/BrowserTime/BlazorTime.csproj @@ -1,8 +1,7 @@ - netstandard2.0 - 3.0 + net6.0 true Dustin Gamester A time conversion library for Blazor that allows you to display dates and times in the browsers local time. It can accept both UTC and server time as an input, and automatically display those times in the browsers local time. @@ -15,8 +14,8 @@ - - + + diff --git a/BrowserTime/ToLocal.razor b/BrowserTime/ToLocal.razor index 2173dca..41c9822 100644 --- a/BrowserTime/ToLocal.razor +++ b/BrowserTime/ToLocal.razor @@ -1,21 +1,69 @@ -@inject IJSRuntime JSRuntime +@using System.Reflection; +@inject IJSRuntime JSRuntime - + @code { - [Parameter] - public DateTime DateTime { get; set; } + [Parameter] + public DateTime DateTime { get; set; } - [Parameter] - public string Format { get; set; } + [Parameter] + public string Format { get; set; } - private ElementReference divElement; + private ElementReference divElement; - protected override async Task OnAfterRenderAsync(bool firstRender) - { - if (firstRender) + private bool _created; + + protected override async Task OnAfterRenderAsync(bool firstRender) + { + if (firstRender) + { + await JSRuntime.InvokeVoidAsync("window.blazorTime.updateTag", divElement); + _created = true; + } + } + + protected override async Task OnParametersSetAsync() + { + if (_created) + { + await JSRuntime.InvokeVoidAsync("window.blazorTime.updateTag", divElement); + } + } + + + [JSInvokable] + public static Task BlazorDateFormat(string tagDate, string formatValue) + { + var localDate = DateTimeOffset.Parse(tagDate); + if (formatValue.StartsWith("To")) + { + + string value = string.Empty; + if (formatValue == "ToUniversalTime") + { + var dateValue = localDate.ToUniversalTime(); + value = dateValue.ToString(); + } + else + { + + MethodInfo method = typeof(DateTime).GetMethod(formatValue); + value = method.Invoke(localDate.DateTime, new object[] { }) as string; + } + + return Task.FromResult(value); + } + else + { + return Task.FromResult(localDate.ToString(formatValue)); + } + } + + [JSInvokable] + public static Task BlazorDate(string tagDate) { - await JSRuntime.InvokeVoidAsync("window.blazorTime.updateTag", divElement); + var localDate = DateTimeOffset.Parse(tagDate); + return Task.FromResult(localDate.ToString()); } - } } diff --git a/BrowserTime/wwwroot/blazorTime.js b/BrowserTime/wwwroot/blazorTime.js index 11a482d..5b02f9b 100644 --- a/BrowserTime/wwwroot/blazorTime.js +++ b/BrowserTime/wwwroot/blazorTime.js @@ -1,54 +1,45 @@ window.blazorTime = {}; -// This is a minified version of https://github.com/felixge/node-dateformat/ -// it is so small that I am just including it and renaming the global variable -// rather than requiring the dependancy. -!function (e) { const t = (() => { const e = /d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g, y = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, o = /[^-+\dA-Z]/g; return (r, i, l, M) => { if (1 !== arguments.length || "string" !== d(r) || /\d/.test(r) || (i = r, r = void 0), (r = r || 0 === r ? r : new Date) instanceof Date || (r = new Date(r)), isNaN(r)) throw TypeError("Invalid date"); const D = (i = String(t.masks[i] || i || t.masks.default)).slice(0, 4); "UTC:" !== D && "GMT:" !== D || (i = i.slice(4), l = !0, "GMT:" === D && (M = !0)); const u = () => l ? "getUTC" : "get", T = () => r[u() + "Date"](), h = () => r[u() + "Day"](), c = () => r[u() + "Month"](), g = () => r[u() + "FullYear"](), f = () => r[u() + "Hours"](), N = () => r[u() + "Minutes"](), p = () => r[u() + "Seconds"](), H = () => r[u() + "Milliseconds"](), S = () => l ? 0 : r.getTimezoneOffset(), b = () => m(r), F = { d: () => T(), dd: () => a(T()), ddd: () => t.i18n.dayNames[h()], DDD: () => s({ y: g(), m: c(), d: T(), _: u(), dayName: t.i18n.dayNames[h()], short: !0 }), dddd: () => t.i18n.dayNames[h() + 7], DDDD: () => s({ y: g(), m: c(), d: T(), _: u(), dayName: t.i18n.dayNames[h() + 7] }), m: () => c() + 1, mm: () => a(c() + 1), mmm: () => t.i18n.monthNames[c()], mmmm: () => t.i18n.monthNames[c() + 12], yy: () => String(g()).slice(2), yyyy: () => a(g(), 4), h: () => f() % 12 || 12, hh: () => a(f() % 12 || 12), H: () => f(), HH: () => a(f()), M: () => N(), MM: () => a(N()), s: () => p(), ss: () => a(p()), l: () => a(H(), 3), L: () => a(Math.floor(H() / 10)), t: () => f() < 12 ? t.i18n.timeNames[0] : t.i18n.timeNames[1], tt: () => f() < 12 ? t.i18n.timeNames[2] : t.i18n.timeNames[3], T: () => f() < 12 ? t.i18n.timeNames[4] : t.i18n.timeNames[5], TT: () => f() < 12 ? t.i18n.timeNames[6] : t.i18n.timeNames[7], Z: () => M ? "GMT" : l ? "UTC" : (String(r).match(y) || [""]).pop().replace(o, "").replace(/GMT\+0000/g, "UTC"), o: () => (S() > 0 ? "-" : "+") + a(100 * Math.floor(Math.abs(S()) / 60) + Math.abs(S()) % 60, 4), p: () => (S() > 0 ? "-" : "+") + a(Math.floor(Math.abs(S()) / 60), 2) + ":" + a(Math.floor(Math.abs(S()) % 60), 2), S: () => ["th", "st", "nd", "rd"][T() % 10 > 3 ? 0 : (T() % 100 - T() % 10 != 10) * T() % 10], W: () => b(), WW: () => a(b()), N: () => (() => n(r))() }; return i.replace(e, e => e in F ? F[e]() : e.slice(1, e.length - 1)) } })(); t.masks = { default: "ddd mmm dd yyyy HH:MM:ss", shortDate: "m/d/yy", paddedShortDate: "mm/dd/yyyy", mediumDate: "mmm d, yyyy", longDate: "mmmm d, yyyy", fullDate: "dddd, mmmm d, yyyy", shortTime: "h:MM TT", mediumTime: "h:MM:ss TT", longTime: "h:MM:ss TT Z", isoDate: "yyyy-mm-dd", isoTime: "HH:MM:ss", isoDateTime: "yyyy-mm-dd'T'HH:MM:sso", isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'", expiresHeaderFormat: "ddd, dd mmm yyyy HH:MM:ss Z" }, t.i18n = { dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], timeNames: ["a", "p", "am", "pm", "A", "P", "AM", "PM"] }; const a = (e, t) => { for (e = String(e), t = t || 2; e.length < t;)e = "0" + e; return e }, s = ({ y: e, m: t, d: a, _: s, dayName: m, short: n = !1 }) => { const d = new Date, y = new Date; y.setDate(y[s + "Date"]() - 1); const o = new Date; o.setDate(o[s + "Date"]() + 1); return (() => d[s + "FullYear"]())() === e && (() => d[s + "Month"]())() === t && (() => d[s + "Date"]())() === a ? n ? "Tdy" : "Today" : (() => y[s + "FullYear"]())() === e && (() => y[s + "Month"]())() === t && (() => y[s + "Date"]())() === a ? n ? "Ysd" : "Yesterday" : (() => o[s + "FullYear"]())() === e && (() => o[s + "Month"]())() === t && (() => o[s + "Date"]())() === a ? n ? "Tmw" : "Tomorrow" : m }, m = e => { const t = new Date(e.getFullYear(), e.getMonth(), e.getDate()); t.setDate(t.getDate() - (t.getDay() + 6) % 7 + 3); const a = new Date(t.getFullYear(), 0, 4); a.setDate(a.getDate() - (a.getDay() + 6) % 7 + 3); const s = t.getTimezoneOffset() - a.getTimezoneOffset(); t.setHours(t.getHours() - s); const m = (t - a) / 6048e5; return 1 + Math.floor(m) }, n = e => { let t = e.getDay(); return 0 === t && (t = 7), t }, d = e => null === e ? "null" : void 0 === e ? "undefined" : "object" != typeof e ? typeof e : Array.isArray(e) ? "array" : {}.toString.call(e).slice(8, -1).toLowerCase(); "function" == typeof define && define.amd ? define(() => t) : "object" == typeof exports ? module.exports = t : e.blazorDateFormat = t }(this); - window.blazorTime = { - init: function () { - var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; - var observer = new MutationObserver(function (mutations, observer) { - for (var i = 0; i < mutations.length; i++) - { - var target = mutations[i].target; - if (target.nodeName == "UTC-TO-LOCAL") { - window.blazorTime.updateTag(target); - } - } - console.log(mutations); - }); - - //watch for elements that have the blazor-time-observer attribute - observer.observe(document, { - attributes: true, - attributeFilter: ["blazor-time-observer"], - subtree: true, - }); - }, updateTag: function (htmlNode) { //get date from tag contents - var utctimeval = htmlNode.attributes["blazor-time-observer"].value; + var utctimeval = htmlNode.attributes["data-blazor-time-observer"].value; var tagDate = new Date(utctimeval); //get format from tag - var format = htmlNode.attributes["format"]; + var format = htmlNode.attributes["data-format"]; var formatValue = null; if (format) { formatValue = format.value; } + var timeZoneOffset = (tagDate.getTimezoneOffset() / 60) * -1; + var offsetString = timeZoneOffset > 0 ? "+" + timeZoneOffset : timeZoneOffset; + var isoDate = tagDate.getFullYear() + "-" + + `${(tagDate.getMonth() + 1)}`.padStart(2, '0') + "-" + + `${tagDate.getDate()}`.padStart(2, '0') + "T" + + `${tagDate.getHours()}`.padStart(2, '0') + ":" + + `${tagDate.getMinutes()}`.padStart(2, '0') + ":" + + `${tagDate.getSeconds()}`.padStart(2, '0') + + offsetString; + //set contents of display tag if (formatValue) { - htmlNode.innerHTML = blazorDateFormat(tagDate, formatValue); + DotNet.invokeMethodAsync('BlazorTime', 'BlazorDateFormat', isoDate, formatValue) + .then(data => { + htmlNode.innerHTML = data; + }); } else { - htmlNode.innerHTML = blazorDateFormat(tagDate); + DotNet.invokeMethodAsync('BlazorTime', 'BlazorDate', isoDate) + .then(data => { + htmlNode.innerHTML = data; + }); } }, updateAllTags: function () { //convert existing display tags - var timeTags = document.getElementsByTagName("utc-to-local") + var timeTags = document.getElementsByClassName("blazor-time") for (var i = 0; i < timeTags.length; i++) { //get tag var currentTag = timeTags[i]; @@ -56,4 +47,3 @@ window.blazorTime = { } } }; -window.blazorTime.init();