Search code examples
c#asp.netazuredatetimeazure-webjobs

Hi, I am trying to run a web job in Azure app service but it is throwing Error related to Datetime


I running a webjob in Azure app service which will get the current datetime and do some operation. but this works fine when I run it in my local machine (I am creating a webjob using a .Net console application).Once I try to run it as Webjob then I am getting this error.

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)

for more details please find the code below

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();
        }

    }
}

The error is thrown when constructor is being called. Please Help


Solution

  • There are several problems with this line of code:

    datetime = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"));
    
    • DateTime.Now uses the system's local time zone. In the cloud this is UTC by default.

      • Since you are using Azure web jobs, you could set the WEBSITE_TIME_ZONE app setting, but only on Windows. If you're running on Linux, this won't work.
      • A better option is to use DateTime.UtcNow and then convert to a specific time zone using TimeZoneInfo.ConvertTime if necessary.
    • In your string format, you are using hh which is for hours 1-12 on a 12-hour clock. Thus, if the time is 13:00 or later, you will lose 12 hours when you parse it. HH is for hours of a 24-hour clock.

    • In your string format, you are using dd/MM/yyyy date format. That may be your format locally, but by default in Azure the CurrentCulture is the InvariantCulture, which uses MM/dd/yyyy format. You get the error because you're trying to parse a value like 15/04/2021 by treating 15 as a month, which is out of range.

    • One should never ever create a string just to parse it again in the same code. There's absolutely no reason for that. If your intent was to truncate fractional seconds, you can do that with:

      datetime = datetime.AddTicks(-datetime.Ticks % TimeSpan.TicksPerSecond);
      

    Putting it all together, you should probably be doing the following:

    // 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);
    

    The above will avoid any impact of culture settings because there's no parsing or formatting going on.

    Also, you should remove Console.ReadKey(); - It will hang your web job.