Chart shows wrong dates at X axis - c#

I am reading date/time and data from a csv file and store this in a line chart. My date/time string is 1-1-2014 21:55:42 or 18-02-2014 00:00:00 which is actually the first entry and i have for a couple of hours data.
First i'm setting the chartArea X axis lablestyle to the proper format: "d-M-yyyy HH:mm:ss".
Then i parse my actual date string to a DateTime format using the same format as above: d-M-yyyy HH:mm:ss. And add the data to the chart.
I ensure you my date is correct:
And my code:
private void button2_Click_1(object sender, EventArgs e)
{
string line;
char[] delimiters = { ';', ',', '|' };
chart1.Series["Series1"].XValueType = ChartValueType.Time;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "d-M-yyyy HH:mm:ss";
chart1.Series["Series1"].Points.Clear();
using (System.IO.StreamReader sr = new System.IO.StreamReader(filename))
{
while (!sr.EndOfStream)
{
line = sr.ReadLine();
DateTime newDateTime = new DateTime();
string[] part = line.Split(delimiters);
Console.WriteLine(part[0]);
newDateTime = DateTime.ParseExact(
part[0],
"d-M-yyyy HH:mm:ss",
CultureInfo.InvariantCulture
);
chart1.Series["Series1"].Points.AddXY(newDateTime, part[5]);
}
}
chart1.Refresh();
}

Problem : You have set the Custom Format for X-Axis as d-M-yyyy HH:mm:ss but you are just providing the datetime without formatting it.
Replace This:
chart1.Series["Series1"].Points.AddXY(newDateTime, part[5]);
With This:
chart1.Series["Series1"].Points.AddXY(
newDateTime.ToString("d-M-yyyy HH:mm:ss"), part[5]);

Related

DateTime.ParseExact

C# is kicking my butt...
I have a text file I'm splitting in hopes to insert into SQL. I need a swift shove in the right direction!
An excerpt from the file I am capturing is below and I am splitting on " - "
2020-06-25-13.23.04.220000 - Running MRP for Site
I can split the two parts just fine.
console_output
But can't seem to get the date into a format that is valid for my SQL insert. I think, but could be completely wrong that I need to reformat this date string using some REPLACE commands.
If I try and use DateTime.ParseExact using my non-working code below I receive a System.FormatException:String was not recognized as valid on my DateTime.ParseExact line.
foreach (string line in lines)
{
if (line.Contains("Running MRP for Site"))
{
List<string> s = new List<string>(
line.Split(new string[] { " - " }, StringSplitOptions.None));
Console.WriteLine(s[0].ToString());
Console.WriteLine(s[1].ToString());
string format = "yyyy-MM-dd-hh:mm:ss:ffffff";
string date = s[0].ToString().Replace('.', ':');
DateTime dt = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
/*
if (conn.State != ConnectionState.Open)
{
conn = new SqlConnection { ConnectionString = Properties.Settings.Default.ConnectionString };
conn.Open();
}
{
String query = #"INSERT INTO
It's the hh. That's a 12-hour clock. You need HH for a 24-hour clock. See Custom date and time format strings - the "HH" custom format specifier.
Here it is in the form of a unit test that takes the input string and verifies that the result is correct (although perhaps crudely.)
[TestMethod]
public void ParseDateTimeTest()
{
var input = "2020-06-25-13.23.04.220000 - Running MRP for Site";
var firstSegment = input.Split(new string[] { " - " }, StringSplitOptions.None)[0];
string format = "yyyy-MM-dd-HH.mm.ss.ffffff";
var parsed = DateTime.ParseExact(firstSegment, format, CultureInfo.InvariantCulture);
Assert.AreEqual(13, Math.Truncate((parsed - new DateTime(2020, 6, 25)).TotalHours));
}

How do you convert date format to yyMMdd in cell click event?

var dateString1 = row.Cells["order_date"].Value.ToString();
txt_lot2.Text = row.Cells["lot_no"].Value.ToString() + " - " + dateString1;
This is string I am pulling from database on DataGridView. Right now it is in yy-MM-dd hh:mm:ss format. I want this value to be converted to yyMMdd when I click the cell. How do I convert this? Output should be something like:
lot_no - order date in yyMMdd
ex of original) K123-19-08-26 12:00:00 AM
ex of to be) K123 - 190826
Original database date format is yy-MM-dd hh:mm:ss and yes, I only want to convert to yyMMdd when I do a cell click event to fill up the textBox.
DateTime doesn't have a format of its own. You have to specify the format you want when using ToString().
var format = "yy-MM-dd hh:mm:ss";
var dateFromDB = "19-08-26 08:23:45";
DateTime.TryParseExact(
dateFromDB,
format,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out DateTime result);
Console.WriteLine(result.ToString("yyMMdd"));
No need to convert, just cut 8 chars and remove dashes:
var row = row.Cells["order_date"].Value.ToString(); // yy-mm-dd hh:mm:ss format
row = row.Substring(0, 8); // yy-mm-dd format
row = row.Replace("-", ""); // yymmdd format
row.Cells["order_date"] = row;
You need to handle three main events:
CellBeginEdit: here you will modify the format of the selected cell
CellParsing: here you will to all data conversion you need
CellEndEdit: here you enable the format back
Here a small working example of the code I've used, please note your code will be more complex because it will need to handle multiple columns and better formatting from the start, consider also I'm using edit mode with F2 to show the modified text:
private void DataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) =>
dataGridView1.CurrentCell.Style.Format = "yyMMdd";
private void DataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
DateTime.TryParseExact(dataGridView1.CurrentCell.EditedFormattedValue.ToString(), "yyMMdd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime dateToSaveInDb);
e.Value = dateToSaveInDb;
e.ParsingApplied = true;
dataGridView1.CurrentCell.Style.Format = "yy-MM-dd hh:mm:ss";
}
private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) =>
dataGridView1.CurrentCell.Style.Format = "yy-MM-dd hh:mm:ss";
I've tested this on a DataGridView populated like this
dataGridView1.DataSource = new List<Element> {
new Element{ EditableDate = DateTime.Now.AddDays(-1)},
new Element{ EditableDate = DateTime.Now},
new Element{ EditableDate = DateTime.Now.AddDays(1)}
}; ;
dataGridView1.EditMode = DataGridViewEditMode.EditOnF2;
Here the example class used
public class Element { public DateTime EditableDate { get; set; } }

Excel date format using EPPlus

I'm having trouble with format my cells to Date.
FileInfo info = new FileInfo(path);
using (ExcelPackage package = new ExcelPackage(info))
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add(sheetName);
ws.Cells[3, 1].Style.Numberformat.Format = "yyyy-mm-dd";
ws.Cells["A3"].Formula = "=DATE(2014,10,5)";
}
Output from this in Excel: 41 917,00
Why is this not working?
I agree with Yosoyke. You're probably targeting the wrong cells. You can try:
ws.Cells["A3"].Style.Numberformat.Format = "yyyy-mm-dd";
ws.Cells["A3"].Formula = "=DATE(2014,10,5)";
worksheet.Cells["YOURDATECELL_OR_YOURDATECELLRANGE"].Style.Numberformat.Format = "mm-dd-yy";
if you use the formula mentioned by taraz. do add worksheet.Calculate() in the end.
reference
https://epplus.codeplex.com/wikipage?title=About%20Formula%20calculation
Or instead of using formula, Alternative approach
private static decimal GetExcelDecimalValueForDate(DateTime date)
{
DateTime start = new DateTime(1900, 1, 1);
TimeSpan diff = date - start;
return diff.Days + 2;
}
Reference
worksheet.Cells["A2"].Value = GetExcelDecimalValueForDate(Convert.ToDateTime('2016-04-29'));
worksheet.Cells["A2"].Style.Numberformat.Format = "mm-dd-yy";//or m/d/yy h:mm
By Default when excel saves a date field it saves it as numFormatId 14(Look at the xml files in the xls). This ensure the date formats correctly in any country when the file is opened.
In Epplus mm-dd-yy translates to numFormatId 14 for excel.
This will ensure that when the file is opened in any country the date will be formatted correctly based on the country's short date settings.
Also noticed m/d/yy h:mm formats correctly for any country.
var dateColumns = from DataColumn d in dt.Columns
where d.DataType == typeof(DateTime) || d.ColumnName.Contains("Date")
select d.Ordinal + 1;
foreach (var dc in dateColumns)
{
worksheet.Cells[2, dc, rowCount + 2, dc].Style.Numberformat.Format = "mm/dd/yyyy hh:mm:ss AM/PM";
}
it will format all the columns with header Date to specific format given/ provided
I was having the same problem with my CSV to be transformed. I was able to do this in a little different manner.
private string ConvertToExcel(string CSVpath, string EXCELPath)
{
try
{
string Filename = System.IO.Path.GetFileNameWithoutExtension(CSVpath);
string DirectoryName = System.IO.Path.GetDirectoryName(CSVpath);
EXCELPath = DirectoryName + "\\" + Filename + ".xlsx";
string worksheetsName = "Report";
bool firstRowIsHeader = false;
var format = new OfficeOpenXml.ExcelTextFormat();
format.Delimiter = '|';
format.EOL = "\n";
using (OfficeOpenXml.ExcelPackage package = new OfficeOpenXml.ExcelPackage(new System.IO.FileInfo(EXCELPath)))
{
string dateformat = "m/d/yy h:mm";
//string dateformat = System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
OfficeOpenXml.ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
worksheet.Cells["A1"].LoadFromText(new System.IO.FileInfo(CSVpath), format, OfficeOpenXml.Table.TableStyles.Medium2, firstRowIsHeader);
worksheet.Column(3).Style.Numberformat.Format = dateformat;
worksheet.Column(5).Style.Numberformat.Format = dateformat;
worksheet.Column(6).Style.Numberformat.Format = dateformat;
worksheet.Column(20).Style.Numberformat.Format = dateformat;
worksheet.Column(21).Style.Numberformat.Format = dateformat;
worksheet.Column(22).Style.Numberformat.Format = dateformat;
package.Save();
}
}
catch (Exception ex)
{
//DAL.Operations.Logger.LogError(ex);
Console.WriteLine(ex);
Console.Read();
}
return EXCELPath;
}
Generic solution which takes IEnumerable (data) it loops through the properties of the generic object finds which is of DateType or nullableDate Type and applies formatting:
//set the list of dateColumns which will be used to formate them
List<int> dateColumns = new List<int>();
//get the first indexer
int datecolumn = 1;
//loop through the object and get the list of datecolumns
foreach (var PropertyInfo in data.FirstOrDefault().GetType().GetProperties())
{
//check if property is of DateTime type or nullable DateTime type
if (PropertyInfo.PropertyType == typeof(DateTime) || PropertyInfo.PropertyType == typeof(DateTime?))
{
dateColumns.Add(datecolumn);
}
datecolumn++;
}
// Create the file using the FileInfo object
var file = new FileInfo(outputDir + fileName);
//create new excel package and save it
using (var package = new ExcelPackage())
{
//create new worksheet
var worksheet = package.Workbook.Worksheets.Add("Results");
// add headers
worksheet.Cells["A1"].LoadFromCollection(data, true);
//format date field
dateColumns.ForEach(item => worksheet.Column(item).Style.Numberformat.Format = "dd-mm-yyyy");
// auto size columns
worksheet.Cells.AutoFitColumns();
//save package
package.SaveAs(file);
}
You can try, If you want using AM/PM
worksheet.Cells[1].Style.Numberformat.Format = "dd/MM/yyyy HH:mm:ss AM/PM";
Following on from the very good Generic solution which takes IEnumerable.. answer we had to go a step further and display different date formatting for different properties. Fro example some columns needed to be displayed as dd/MM/yyyy and others as dd/MM/yyyy hh:mm.
So we added a DisplayFormat annotation with a DataFormatString (representing a DateTime format) to our properties like this:
using System.ComponentModel.DataAnnotations;
...
[DisplayName("Download Date")]
[DisplayFormat(DataFormatString = "dd/MM/yyyy hh:mm")]
public string DownloadDate { get; set; }
...
And then borrowing from Generic solution which takes IEnumerable.. we pulled out the date format string from the DisplayFormat annotation when iterating the properties of the data object:
public void FormatDateColumns(ExcelWorksheet worksheet, IEnumerable<IResult> data)
{
// Dictionary 'key' contains the Index of the column that contains DateTime data
// Dictionary 'value' contains the DateTime format for that column
Dictionary<int, string> dateColumns = new Dictionary<int, string>();
int dateColumnIndex = 1;
// find all the DateTime/DateTime? columns in the data object
foreach (var PropertyInfo in data.FirstOrDefault().GetType().GetProperties())
{
if (PropertyInfo.PropertyType == typeof(DateTime) || PropertyInfo.PropertyType == typeof(DateTime?))
{
string dateTimeFormat = Constants.DefaultDateTimeFormat;
// attempt to get a DataFormatString from a DisplayFormat annotation which may be decorating the Property
// looking for an annotation something like [DisplayFormat(DataFormatString = "dd-MM-yyyy hh:mm")]
if (PropertyInfo.CustomAttributes != null)
{
var dislayFormatAttribute = PropertyInfo.CustomAttributes.Where(x => x.AttributeType.Name == "DisplayFormatAttribute").FirstOrDefault();
if (dislayFormatAttribute != null && dislayFormatAttribute.NamedArguments != null && dislayFormatAttribute.NamedArguments.Count > 0)
{
var displayFormatArg = dislayFormatAttribute.NamedArguments.First();
if (displayFormatArg != null && displayFormatArg.TypedValue != null && displayFormatArg.TypedValue.Value != null)
{
// NOTE: there is probably an easier way to get at this value?
dateTimeFormat = displayFormatArg.TypedValue.Value.ToString();
}
}
}
dateColumns.Add(dateColumnIndex, dateTimeFormat);
}
dateColumnIndex++;
}
if (dateColumns.Count > 0)
{
// apply the formatting
dateColumns.ToList().ForEach(item => worksheet.Column(item.Key).Style.Numberformat.Format = item.Value);
}
}
I wanted to add that the setting of the format was the solution for me. But, I could not get it to work until I set the value property to a DateTime object and not a string. That was the key to making it all work.
I had a similar issue, and even though I was correctly setting the date and applying the proper number format to the cell containing the date, I was seeing the numeric representation of the date.
Turns out that after that, I applied a style, that effectively reset my format.
The code was something like:
ws.Cells["A3"].Style.Numberformat.Format =
System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
ws.Cells["A3"].Value = New DateTime(2021, 10, 15, 23, 16, 0).ToOADate();
and later, I had:
ws.Cells("A3").StyleName = colStyle //colstyle is a style created earlier
To fix that, I needed to apply the NumberFormat.Format after setting the style.
Make sure your cell width is large enough to display your date! This is the problem if the cell displays ### symbols.
A simple fix for this is to autofit the cell width in your worksheet:
ws.Cells.AutoFitColumns();
Complete example with passing a DateTime object:
ws.Cells[3, 1].Style.Numberformat.Format = "yyyy-mm-dd";
ws.Cells[3, 1].Value = new DateTime(2014,10,5);
ws.Cells.AutoFitColumns();
For advanced formatting, look at https://support.microsoft.com/en-us/office/number-format-codes-5026bbd6-04bc-48cd-bf33-80f18b4eae68.
Keep in mind NOT to localize reserved characters of the numberformat code into another language: Write yyyy for the year, not jjjj. If you want to format a number and want the decimal separator, write 0.00, not 0,00.
(Posted this as I keep stumbling over this problem and this question is the first search result.)
Some news:
ws.Cells["A3"].Style.Numberformat.Format = "[$-en-US]yyyy-mmm-dd";
ws.Cells["A3"].Formula = "=DATE(2014,10,5)";

DateTime ParseExact exception

var str = "00:00:00 02/01/1990";
var dt = DateTime.ParseExact(str, "hh:mm:ss dd/MM/yyyy", null);
The above code is throwing an exception "String was not recognized as a valid DateTime."
I thought using ParseExact and specifying the exact format this would be okay. What is wrong with the above?
EDIT:
Solved using invariant culture. Thanks for comments.
var dt = DateTime.ParseExact(str, "HH:mm:ss dd/MM/yyyy", CultureInfo.InvariantCulture);
The "hh" format specifier is for 12-hour AM/PM time, which doesn't support a "00". Try defining it in 24-hour time: HH:mm:ss dd/MM/yyyy
Yes usually in DateTime format the Date comes first before Time. Try this out:
var str = "02/01/1990 00:00:00";
var dt = DateTime.ParseExact(str, "hh:mm:ss dd/MM/yyyy", null);
EDITED: OK so you do one trick to get it done:
var str = "00:00:00 02/01/1990";
var split = str.Split(new char[] { ' ' });
if (split.Length == 2)
str = String.Format("{0} {1}", split[1], split[0]);
var dt = DateTime.ParseExact(str, "hh:mm:ss dd/MM/yyyy", null);

convert datetime to date format dd/mm/yyyy

I have a DateTime object 2/19/2011 12:00:00 AM. I want to convert this object to a string 19/2/2011.
Please help me to convert DateTime to string format.
DateTime dt = DateTime.ParseExact(yourObject.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
First of all, you don't convert a DateTime object to some format, you display it in some format.
Given an instance of a DateTime object, you can get a formatted string in that way like this:
DateTime date = new DateTime(2011, 2, 19);
string formatted = date.ToString("dd/M/yyyy");
As everyone else said, but remember CultureInfo.InvariantCulture!
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)
OR escape the '/'.
You have to pass the CultureInfo to get the result with slash(/)
DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
DateTime.ToString("dd/MM/yyyy") may give the date in dd-MM-yyyy format. This depends on your short date format. If short date format is not as per format, we have to replace character '-' with '/' as below:
date = DateTime.Now.ToString("dd/MM/yyyy").Replace('-','/');
It's simple--tostring() accepts a parameter with this format...
DateTime.ToString("dd/MM/yyyy");
Here is a method, that takes datetime(format:01-01-2012 12:00:00) and returns string(format: 01-01-2012)
public static string GetDateFromDateTime(DateTime datevalue){
return datevalue.ToShortDateString();
}
You can use the ToString() method, if you want a string representation of your date, with the correct formatting.
Like:
DateTime date = new DateTime(2011, 02, 19);
string strDate = date.ToString("dd/MM/yyyy");
In C# 10 you can use DateOnly.
DateOnly date = new(2011, 02, 19);
string output = date.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
If you want the string use -
DateTime.ToString("dd/MM/yyyy")
On my login form I am showing the current time on a label.
public FrmLogin()
{
InitializeComponent();
lblTime.Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");
}
private void tmrTime_Tick(object sender, EventArgs e)
{
lblHora.Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");
}
string currentdatetime = DateTime.Now.ToString("dd'/'MM'/'yyyy");
DateTime.Parse(YOUR_DATE_OBJECT).ToShortDateString();
ToShortDateString() method will help you convert DateTime To Just Date String,format dd/mm/yyyy.
This works for me:
string dateTimeString = "21‎-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30";
dateTimeString = Regex.Replace(dateTimeString, #"[^\u0000-\u007F]", string.Empty);
string inputFormat = "dd-MM-yyyy HH:mm:ss";
string outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
string output = dateTime.ToString(outputFormat);
Console.WriteLine(output);
this is you need and all people
string date = textBox1.Text;
DateTime date2 = Convert.ToDateTime(date);
var date3 = date2.Date;
var D = date3.Day;
var M = date3.Month;
var y = date3.Year;
string monthStr = M.ToString("00");
string date4 = D.ToString() + "/" + monthStr.ToString() + "/" + y.ToString();
textBox1.Text = date4;

Categories