DateTime class common error displayed again - c#

I run into a little common problem with datetime class that I have no idea how to resolve.
I don't know what the error is but I see the troubleshooting tips are displayed as
When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object. Make sure your method arguments are in the right format.
Here is the piece of code I extract from my program,
public IEnumerable<CONTACT_INFO> GetContactInfo(string tableName)
{
DataTable dt = GetUserInfo(tableName);
List<CONTACT_INFO> lst = new List<CONTACT_INFO>();
foreach (DataRow row in dt.Rows)
{
string sDate = "";
if(!string.IsNullOrEmpty(row["birthday"].ToString()))
{
sDate = row["birthday"].ToString();
}
string format = "yyyyMMdd";
System.Globalization.CultureInfo provider =CultureInfo.InvariantCulture;
string datetime = DateTime.Now.ToShortDateString();
if (!string.IsNullOrEmpty(sDate))
{
datetime = DateTime.ParseExact(sDate, format, provider).ToShortDateString();
}
if (row["companyname"].ToString().CompareTo("companylogo") != 0)
{
string profile_time = row["profile_timestamp"].ToString();
if (!string.IsNullOrEmpty(profile_time))
{
CSTimeZone time = new CSTimeZone();
profile_time = time.FromUnix(Convert.ToDouble(profile_time)).ToShortDateString()+" "+
time.FromUnix(Convert.ToDouble(profile_time)).ToLongTimeString();
}
string lastUseNetTime = row["last_used_networktime"].ToString();
if (!string.IsNullOrEmpty(lastUseNetTime))
{
CSTimeZone time = new CSTimeZone();
double sec = Convert.ToDouble(lastUseNetTime) * 60;
lastUseNetTime = time.FromUnix(Convert.ToDouble(sec)).ToShortDateString() + " " +
time.FromUnix(Convert.ToDouble(sec)).ToLongTimeString();
}
string lastOnlineTime = row["lastonline_timestamp"].ToString();
if (!string.IsNullOrEmpty(lastOnlineTime))
{
CSTimeZone time = new CSTimeZone();
lastOnlineTime = time.FromUnix(Convert.ToDouble(lastOnlineTime)).ToShortDateString() + " " +
time.FromUnix(Convert.ToDouble(lastOnlineTime)).ToLongTimeString();
}
lst.Add(new CONTACT_INFO()
{
gender=Convert.ToInt32(row["gender"].ToString()),
timezone=row["timezone"].ToString(),
fullName = row["fullname"].ToString(),
profile_timestamp = profile_time,
last_used_networktime = lastUseNetTime,
lastonline_timestamp = lastOnlineTime,
birthday = string.IsNullOrEmpty(sDate) ? "" : datetime
});
}
}
return lst;
}
The function FromUnix is written as
public DateTime FromUnix(double seconds)
{
DateTime datetime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime();
return datetime.AddSeconds(seconds);
}

I am pretty sure this is a parsing problem
The following line would throw exceptions if the value of sDate is not in the defined format of yyyyMMdd
datetime = DateTime.ParseExact(sDate, format, provider).ToShortDateString();
I would first use TryParseExact instead of a simple Parse since you do not seem to be using try/catch clauses. It might be a good idea to use the debugger to see exactly where your program is failing.
Other example of potential failures in your code are
double sec = Convert.ToDouble(lastUseNetTime) * 60;
Use double.tryParse
Convert.ToInt32(row["gender"].ToString()
If gender turns out not to be a number another exception will be thrown
etc...

Related

Get datetime from database and split it

I am working on a C# program. I created an EF code-first database in which I read in a csv file. This csv file contains a DateTime object. This DateTime object was saved in the database. Now I have to get this DateTime and parse it into the DATE (dd-mm-yyyy) and the TIME (hh:mm:ss.fff). Unfortunately I don't know how to solve this problem.
private readonly PerformanceAnalyseToolContext db;
public HomeController(PerformanceAnalyseToolContext db)
{
this.db = db;
}
public IActionResult ReadCsvData(string csvData) //get csvData String
{
ChartData chartData = new ChartData();
string[] lines = csvData.Split("\n"); //Split after enter
//List<ChartData> chartDataList = new List<ChartData>();
foreach (var line in lines)
{
string[] values = line.Split(','); // SPlit after ,
try //try catch, because if an error occurs the process has to continue
{
chartData = new ChartData { //Create object from csv data
Timestamp = Convert.ToDateTime(values[0] + "." + values[1]),
Function = Convert.ToString(values[2]),
Duration = Convert.ToInt32(values[4]),
IsError = Convert.ToBoolean(values[5])
};
db.ChartDatas.Add(chartData); //Save object into database
db.SaveChanges();
}
catch(Exception exc)
{
exc.ToString();
}
}
return View(chartData);
}
public List<ChartDatanDTO> GetDataForChart(string function)
{ //here i get the Data from the DB
return db.ChartDatas
.Where(x => x.Function == function)
.Select(x => new ChartDatanDTO
{
durat = x.Duration,
err = x.IsError,
time =x.Timestamp
})
.ToList();
}
You can specify the format of your DateTime in the ToString method.
time = x.Timestamp.ToString("dd-MM-yyyy hh:mm:ss.fff")
If you need them separated you can do ToString twice.
date = x.Timestamp.ToString("dd-MM-yyyy")
time = x.Timestamp.ToString("hh:mm:ss.fff")
You can use DateTime.ParseExact() method
DateTime dt = DateTime.ParseExact(yourDateTime, "yyyy/MM/DD", CultureInfo.InvariantCulture);
for more info you can check:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/parsing-datetime
Convert function directly doesn't work in LINQ,
So you also can use DBFunctions to truncate time and SqlFunctions.DatePart to get time
........
.Select(x => new ChartDatanDTO
{
date = DbFunctions.TruncateTime(x.YourDateTime),
time = SqlFunctions.DatePart("hh", x.YourDateTime) + ":" +
SqlFunctions.DatePart("mm", x.YourDateTime) +":" +
SqlFunctions.DatePart("ss", x.YourDateTime)
});

Convert dd/mm/yyyy string to yyyy-dd-mm DateTime in c#

How do I convert 13/05/2019 (dd/mm/yyyy) string to 2019-13-05 (YYYY-dd-mm) DateTime Datatype in c#,sql sever Expects YYYY-dd-mm format datatype
string dateTime = "05/13/2019";
if (animalAdoption.AdoptionId != 0)
{
AnimalsAndBirdsAdoption animalsAndBirdsAdoption = new AnimalsAndBirdsAdoption()
{
AnimalsAndBirdsId = animalAdoption.AnimalId,
DonarDetailsId = userId,
Term = model.Term,
PeriodOfAdoption = dateTime,
isActive = true,
Amount = animalAdoption.amount
};
if (context.AnimalsAndBirdsAdoptions.Any(e => e.Id == animalAdoption.AdoptionId))
{
context.AnimalsAndBirdsAdoptions.Attach(animalsAndBirdsAdoption);
}
else
{
context.AnimalsAndBirdsAdoptions.Add(animalsAndBirdsAdoption);
}
}
this out-put I get
You can do it simply using below example with using your required format:
string dateTime = "05/13/2019";
CultureInfo provider = CultureInfo.InvariantCulture;
// It throws Argument null exception
DateTime dateTime10 = DateTime.ParseExact(dateTime, "yyyy/dd/mm", provider);
string dateTime = "13/05/2019";
var splittedDateTime = dateTime.Split('/');
DateTime myDate = new DateTime(int.Parse(splittedDateTime[2]), int.Parse(splittedDateTime[1]), int.Parse(splittedDateTime[0]));
To convert a UK date string to a DateTime
public DateTime? ToDateTime(string text)
{
DateTime? returnValue = null;
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-GB");
DateTime d = new DateTime();
if(DateTime.TryParse(text, cultureInfo, System.Globalization.DateTimeStyles.None, out d))
{
returnValue = d;
}
return returnValue;
}
To convert a DateTime to string yyyy-MM-dd:
public string ToBigEndianString(DateTime? date)
{
string returnValue = null;
if(date != null)
{
returnValue = date.Value.ToString("yyyy-MM-dd");
}
return returnValue;
}
Then you can put them together:
public string ToBigEndianString(string ukDate)
{
DateTime? d = ToDateTime(ukDate);
return ToBigEndianString(d);
}
But you could pass in a DateTime to a SQL stored procedure.
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparametercollection.addwithvalue?view=netframework-4.8
Change the datatype of PeriodOfAdoption to Type System.DateTime
and then you can initialise the property using the DateTime constructor which has many overloads.
If your string format is always in the form yyyy-dd-mm based on: '2019-13-05'
you can extract the year the month and the day, by perhaps using .Split('-') string function or if its the format: '2019/13/05' you can split on '/' e.g. .Split('/').
Then you can create your DateTime object using the constructor like so (you can view them here https://learn.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.8):
constructor:
public DateTime (int year, int month, int day);
initialisation:
PeriodOfAdoption = new DateTime(2019, 5, 13)
so putting it together:
var dateTime = '2019/13/05';
var dateParts = dateTime.Split('/');
PeriodOfAdoption = new DateTime(Int32.parse(dateParts[0]), Int32.parse(dateParts[1]), Int32.parse(dateParts[2]));
If you need a string in the c# side, this is very simple in C# and there are many examples online

C# If else program not recognizing the if statement and only taking the else

Hi i have the following code, the problem i am facing is no matter if the folder exists it still continues to send the email instead of ignoring to send it.
What can i change to get this working.
static void Main(string[] args)
{
string yesterdaydate = DateTime.Now.AddDays(-1).ToString("yyyy-mm-dd");
string[] SplitDate = yesterdaydate.Split('-');
string year = SplitDate[0];
string month = SplitDate[1];
string day = SplitDate[2];
string path = Path.Combine("C:\\Users\\ales\\Desktop\\test", year, month, day);
if (Directory.Exists(path))
{
//do nothing
}
else
{
string fromAddress = "noreply#arm.com";
string toAddress = "alese#arm.com";
string subject = "error";
string body = "failed to sync";
krysalis_email.EmailClient email = new krysalis_email.EmailClient();
krysalis_email.EmailClient.EmailResponse emailResponse = email.sendBasicMail(new object[] {toAddress}, fromAddress, subject, body, false, "smtp.za.arm.com",
new string[] {"", ""}, false, null);
if (emailResponse != null)
{
}
}
}
The problem is in your date format to string. You are using mm which is minutes. Use MM to get month. Keep in mind that MM format will give you month with leading zero, for example 08
If you want to use string splitting, then change the code to
string yesterdaydate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
But as others pointing, the better way to get values is to use DateTime instead of parsing string. Here is an example:
DateTime yesterdaydate = DateTime.Now.AddDays(-1);
string year = yesterdaydate.Year.ToString();
string month = yesterdaydate.Month.ToString("D2");//D2 to format number to be zero-padded
string day = yesterdaydate.Day.ToString("D2");
string path = Path.Combine("C:\\Users\\ales\\Desktop\\test", year, month, day);

Unable to get date in proper format when days are less than 12 FROM EXCEL in C#

I am new to c# . When i am trying to import excel sheet using the following code :
try
{
DateTime date = DateTime.FromOADate(w.Cells[i, index[j]].value2);
string str = date.ToString("d-M-yyyy");
dRow[j] = Convert.ToDateTime(str, ci);
}
catch (Exception)
{
try
{
String ss1 = (String)w.Cells[i, index[j]].value2;
if (ss1 == null || ss1.Equals("NIL") || ss1.Equals("."))
{
dRow[j] = DBNull.Value;
}
else if (ss1 != null)
{
DateTime dat = Convert.ToDateTime(ss1);
ss1 = dat.ToString(ci.NumberFormat);
dRow[j] = Convert.ToDateTime(ss1,null);
}
else
{
dRow[j] = DBNull.Value;
}
}
catch (Exception ex1)
{
try
{
String ss2 = (String)w.Cells[i, index[j]].value2;
if (ss2 != null)
{
String ss2_t = ss2.Trim();
DateTime da = DateTime.ParseExact(ss2_t, "d-M-yyyy", null);
dRow[j] = da;
}
else
{
dRow[j] = DBNull.Value;
}
}
catch (Exception ex2)
{
try
{
String ss3 = (String)w.Cells[i, index[j]].value2;
if (ss3 != null)
{
String ss3_t = ss3.Trim();
DateTime da1 = DateTime.ParseExact(ss3, "d-M-yyyy", CultureInfo.InvariantCulture);
dRow[j] = da1;
}
else
{
dRow[j] = DBNull.Value;
}
}
catch (Exception)
{
dRow[j] = DBNull.Value;
}
}
}
Everything works fine untill date has day value less than 12. For example if DATE is 23-07-2013 it works fine . but if DATE is 7-5-2013 then DateTime.FromOADate() convert it into 5-July-2013 . I am totally stuck. Please help me as soon as possible.
If you mean the difficulty is with your str variable then use this format:
string str = date.ToString("dd-mm-yyyy");
Update
The argument passed to DateTime.FromOADate() is a double which is obviously not format sensitive. So I'm not exactly sure why you'd need to convert it to a string and then back to a date. Is it possible that dRow[j] = date is all you need?
If the returned valued of FromOADate() is incorrect then you need to return to your source data, ie Excel. You would need to adjust the format settings there or, if that data was imported, run a small VBA macro to convert the values yourself.
I'm not sure where in the code you are seeing the "d-M-yyyy" v. "M-d-yyy" difference. If you are looking at your dRow[j] variable then this will abide by your defined CultureInfo, presumably the ci variable.
Below is some code that shows three ways of managing date string conversions, the first two manipulate the CultureInfo, the third is pure manual string parsing.
Have a play to see if any of these suit your needs, but I still return to my original question of "do you need to go 'date - string - date' at all"?
DateTime date = DateTime.FromOADate(42491);
string str = date.ToString("d-M-yyyy");
Console.WriteLine(str);
//CultureInfos
CultureInfo ciGB = new CultureInfo("en-GB", false);
CultureInfo ciUS = new CultureInfo("en-US", false);
//ToDateTime version
DateTime dateGB = Convert.ToDateTime(str, ciGB);
DateTime dateUS = Convert.ToDateTime(str, ciUS);
Console.WriteLine("ToDateTime: GB = {0}, US = {1}", dateGB, dateUS);
//ParseExact version
DateTime parsedGB = DateTime.ParseExact(str,"d-M-yyyy", ciGB);
DateTime parsedUS = DateTime.ParseExact(str, "M-d-yyyy", ciUS);
Console.WriteLine("ParseExact: GB = {0}, US = {1}", parsedGB, parsedUS);
//Manual parsing
var parts = str.Split('-');
int item1 = int.Parse(parts[0]);
int item2 = int.Parse(parts[1]);
int item3 = int.Parse(parts[2]);
DateTime manualGB = new DateTime(item3, item2, item1);
DateTime manualUS = new DateTime(item3, item1, item2);
Console.WriteLine("Manual: GB = {0}, US = {1}", manualGB, manualUS);

Getting an error when DateTime converted to a string returns null

I have the following code block with in one of my controllers, this code returns two date strings formatted a certain way based on culture for my View to consume.
string dateStringForSystem = "";
string dateStringForActiveMetrics = "";
string cultureConfigKey = System.Configuration.ConfigurationManager.AppSettings["InstanceCulture"];
DateTime? lastEntryDateForSystem = null;
DateTime? lastEntryDateForActiveMetrics = null;
DataSet dSet = DataHelper.Measurements_GetLastMeasurement(userSession.UserIDNative);
foreach (DataRow dr in dSet.Tables[0].Rows)
{
lastEntryDateForSystem = (DateTime?)dr["LastMeasurementWhen"];
lastEntryDateForActiveMetrics = (DateTime?)dr["LastMeasurementForActiveGoalsWhen"];
}
// Format viewdata dates based on culture and convert it to string
if (cultureConfigKey == "en" )
{
ViewData["DateStringForSystem"] = dateStringForSystem = String.Format("{0:MM/dd/yy}", lastEntryDateForSystem);
ViewData["DateStringForActiveMetrics"] = dateStringForActiveMetrics = String.Format("{0:MM/dd/yy}", lastEntryDateForActiveMetrics);
}
else
{
ViewData["DateStringForSystem"] = dateStringForSystem = String.Format("{0:dd/MM/yy}", lastEntryDateForSystem);
ViewData["DateStringForActiveMetrics"] = dateStringForActiveMetrics = String.Format("{0:dd/MM/yy}", lastEntryDateForActiveMetrics);
}
With in the View code I store and use the view data as such. But if the strings return null I'm getting an error. Is null not returned as a string even when I convert the dateTime to a string?
var dateStringForSystem = ViewData["DateStringForSystem"];
var dateStringForActiveMetrics = ViewData["DateStringForActiveMetrics"];
#if (dateStringForSystem == "")
{
// some html
}
else if (dateStringForActiveMetrics != "")
{
<span>#dateStringForActiveMetrics</span>
}
Still pretty new to C#, so any recommendations on cleaning this code up is also greatly appreciated :) Thanks!

Categories