c# - 嗨,我正在尝试在 Azure 应用服务中运行 Web 作业,但它抛出与日期时间相关的错误
问题描述
我在 Azure 应用服务中运行一个网络作业,它将获取当前日期时间并执行一些操作。但是当我在本地机器上运行它时它工作正常(我正在使用 .Net 控制台应用程序创建一个 webjob)。一旦我尝试将它作为 Webjob 运行,我就会收到这个错误。
Unhandled Exception: System.FormatException: String was not recognized as a valid DateTime.
System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
System.Convert.ToDateTime(String value)
有关更多详细信息,请在下面找到代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.IO;
namespace Zoho_API_Services
{
class Items
{
#region DateTime
public DateTime datetime { get; set; }
public static DateTime Current_time { get; set; }
public static DateTime Target_time { get; set; }
//Constructor to get current date time
public Items()
{
datetime = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"));
}
#endregion
public static void Main()
{
//Call the constructor
Items obj = new Items();
//Initialize Current time and Target time
Current_time = obj.datetime;
Target_time = Current_time.AddMinutes(55);
if (Current_time >= Target_time)
{
//Reset the Current time and Target time
Current_time = obj.datetime;
Target_time = Current_time.AddMinutes(55);
// Do something
}
else
{
// Do Something
}
Console.ReadKey();
}
}
}
调用构造函数时会引发错误。请帮忙
解决方案
这行代码有几个问题:
datetime = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"));
DateTime.Now
使用系统的本地时区。在云中,默认为 UTC。- 由于您使用的是 Azure Web 作业,因此您可以设置
WEBSITE_TIME_ZONE
应用程序设置,但仅限于 Windows。如果您在 Linux 上运行,这将不起作用。 - 更好的选择是使用,然后在必要
DateTime.UtcNow
时使用转换为特定时区。TimeZoneInfo.ConvertTime
- 由于您使用的是 Azure Web 作业,因此您可以设置
在您的字符串格式中,您使用
hh
的是 12 小时制的 1-12 小时。因此,如果时间是 13:00 或更晚,解析时会损失 12 个小时。HH
是 24 小时制的几个小时。在您的字符串格式中,您使用的是
dd/MM/yyyy
日期格式。这可能是您在本地的格式,但在 Azure 中默认情况下CurrentCulture
是InvariantCulture
,它使用MM/dd/yyyy
格式。您收到错误是因为您试图解析一个值,例如15/04/2021
将 15 视为一个月,这超出了范围。永远不应该创建一个字符串只是为了在相同的代码中再次解析它。绝对没有理由这样做。如果您的意图是截断小数秒,您可以这样做:
datetime = datetime.AddTicks(-datetime.Ticks % TimeSpan.TicksPerSecond);
综上所述,您可能应该执行以下操作:
// I chose the time zone based on the location in your Stack Overflow user profile.
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("India Standard time"); // or "Asia/Kolkata" on Linux
// Get the UTC time and convert to the given time zone.
datetime = TimeZoneInfo.ConvertTime(DateTime.UtcNow, tz);
// Truncate to seconds.
datetime = datetime.AddTicks(-datetime.Ticks % TimeSpan.TicksPerSecond);
以上将避免文化设置的任何影响,因为没有进行解析或格式化。
此外,您应该删除Console.ReadKey();
- 它会挂起您的网络作业。
推荐阅读
- java - AWT 和 Swing 组件未正确呈现
- python - 将列表中的 nan 值替换为元素数据类型之后的另一个值
- sql - 临时表既存在又不存在
- python - 如何从代码运行 tensorflow 对象检测 api (model_main_tf2)?
- cordova - 在应用中心添加应用进行代码推送时无法选择“Cordova”项
- javascript - 客户端 zip 多次获取
- linux-kernel - 当 dd 时,nvme 超时如何受 pcie 控制器“范围”dts 属性的影响
- laravel - Laravel mix 不能在 scss 和 js 文件之间共享变量
- html - 将第一个 flex 项目对齐到 flex end
- javascript - 当渲染一行/列中所有堆叠条的总值时,Recharts 堆叠条正在绘制许多标签。如何让它只渲染一个?