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)";
Related
When I try this code:
string value = "220510"; // The `value` variable is always in this format
string key = "30";
string title;
switch (key)
{
case "30":
title = "Date: ";
Console.WriteLine($"{title} is {value}");
break;
}
the output looks like this:
My problem is that I don't know how to insert the '-' character to separate the month, day and year because I want it to display:
Date: is 22-05-10
Please show me how to parse it.
If you have a DateTime object:
oDate.toString("yy-MM-dd");
If you have a string you can either:
sDate = sDate.Insert(2,"-");
sDate = sDate.Insert(5,"-");
or go through DateTime again (for whatever reason):
string sDate = "220510";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime sDate = Convert.ParseExact(iDate, "yyMMdd", provider);
sDate.toString("yy-MM-dd");
Your question is: How do I parse the string 220510 date format so the value comes out as 22-05-10?
In this specific case, consider using the string.Substring method to pick out the digit pairs then use string interpolation to put them back together.
const string raw = "220510";
// To do a simple parse (not using a DateTime object)
var yearString = raw.Substring(0, 2);
var monthString = raw.Substring(2, 2);
var dayString = raw.Substring(4, 2);
var string_22_05_10 = $"{yearString}-{monthString}-{dayString}";
Console.WriteLine(string_22_05_10);
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; } }
The problem I am facing is that in a cell of an Excel sheet, a date is written. The cell is formatted with custom-format like:
[$-de]dd/mm/yyyy (dddd)
But only the (dddd) part is processed to give me "Sonntag" (Sunday in German language).
The datetime format is not fixed even though I have written the culture as "de" for the custom format. Is there any way to achieve the following result without altering the datetime format(yyyy-mm-dd)?
Tried Output Expected output
-------- ----------------------- -------------------
[$-fr]yyyy-mm-dd (dddd) => 2019-07-31 (dimanche) 31/7/2019 (dimanche)
[$-de]yyyy-mm-dd (dddd) => 2019-07-31 (Sonntag) 31.7.2019 (Sonntag)
[$-en]yyyy-mm-dd (dddd) => 2019-07-31 (Sunday) 7.31.2019 (Sunday)
Since you are specifying the exact data format in the string (the yyyy-mm-dd), excel will have to respect it when it opens. AFAIK, excel does not have a true "default" format that matches what you are looking for. If you open Excel and specify the format of a cell you can set the Culture/Country but you would still have to choose the format - the first one usually uses / as the separator.
But if you want to use what is in .NET, you could use CultureInfo.DateTimeFormat to get what I think you are after:
CultureInfo c;
var dt = new DateTime(2019,7,31);
c = new CultureInfo("fr-FR");
Console.WriteLine($"{c}: {c.DateTimeFormat.ShortDatePattern}");
Console.WriteLine(dt.ToString($"{c.DateTimeFormat.ShortDatePattern} (dddd)", c.DateTimeFormat));
Console.WriteLine();
c = new CultureInfo("de-DE");
Console.WriteLine($"{c}: {c.DateTimeFormat.ShortDatePattern}");
Console.WriteLine(dt.ToString($"{c.DateTimeFormat.ShortDatePattern} (dddd)", c.DateTimeFormat));
Console.WriteLine();
c = new CultureInfo("en-EN");
Console.WriteLine($"{c}: {c.DateTimeFormat.ShortDatePattern}");
Console.WriteLine(dt.ToString($"{c.DateTimeFormat.ShortDatePattern} (dddd)", c.DateTimeFormat));
Console.WriteLine();
Will give you this in the output:
fr-FR: dd/MM/yyyy
31/07/2019 (mercredi)
de-DE: dd.MM.yyyy
31.07.2019 (Mittwoch)
en-EN: M/d/yyyy
7/31/2019 (Wednesday)
To use in excel do this:
[TestMethod]
public void Culture_Info_Data_Format_Test()
{
//https://stackoverflow.com/questions/56985491/is-there-any-way-to-format-date-cell-in-excel-with-invariant-culture-like-in-c-s
var fileInfo = new FileInfo(#"c:\temp\Culture_Info_Data_Format_Test.xlsx");
if (fileInfo.Exists)
fileInfo.Delete();
using (var pck = new ExcelPackage(fileInfo))
{
var dt = new DateTime(2019, 7, 31);
var workbook = pck.Workbook;
var worksheet = workbook.Worksheets.Add("Sheet1");
worksheet.Column(1).Width = 50;
var c = new CultureInfo("fr-FR");
var format = $"[$-fr]{c.DateTimeFormat.ShortDatePattern} (dddd)";
worksheet.Cells[1, 1].Value = dt;
worksheet.Cells[1, 1].Style.Numberformat.Format = format;
c = new CultureInfo("de-DE");
format = $"[$-de]{c.DateTimeFormat.ShortDatePattern} (dddd)";
worksheet.Cells[2, 1].Value = dt;
worksheet.Cells[2, 1].Style.Numberformat.Format = format;
c = new CultureInfo("en-EN");
format = $"[$-en]{c.DateTimeFormat.ShortDatePattern} (dddd)";
worksheet.Cells[3, 1].Value = dt;
worksheet.Cells[3, 1].Style.Numberformat.Format = format;
pck.Save();
}
}
which gives this:
Try to use below formula in another column/cell, assuming you have a date starting from A1
=TEXT(A1,"mm/dd/yyy (dddd[$-fr])")
Hope it helps!
You can change the text string type from "/" to "." or whatever you want and the language format by changing this element [$-fr]
so I understand how to make global values and the fact that 1. you shouldn't do it and 2. you cannot use a value that was created in a different "context" however, I'm not sure how to correct this problem in my case. I think it will make sense if you read my code
//read in Load Query TestCSV
var sourcePath = #"D:\\Load Query test.csv"; //What is the inital CSV
var delimiter = ",";
var firstLineContainsHeaders = true; //CSV has headers
//creates temp file which takes less time than loading into memory
var tempPath = Path.Combine(#"D:", Path.GetRandomFileName());
var lineNumber = 0;
var splitExpression = new Regex(#"(" + delimiter + #")(?=(?:[^""]|""[^""]*"")*$)");
using (var writer = new StreamWriter(tempPath))
using (var reader = new StreamReader(sourcePath))
{
string line = null;
string[] headers = null;
if (firstLineContainsHeaders)
{
line = reader.ReadLine();
lineNumber++;
if (string.IsNullOrEmpty(line)) return; // file is empty;
headers = splitExpression.Split(line).Where(s => s != delimiter).ToArray();
writer.WriteLine(line); // write the original header to the temp file.
}
var i = 0; //used in 2nd while loop later
string lines = null;//used in next using statement
while ((line = reader.ReadLine()) != null)
{
lineNumber++;
var columns = splitExpression.Split(line).Where(s => s != delimiter).ToArray();
//make sure you always have the same number of columns in a line
if (headers == null) headers = new string[columns.Length];
if (columns.Length != headers.Length) throw new InvalidOperationException(string.Format("Line {0} is missing one or more columns.", lineNumber));
string badDate = "Date entered incorrectly"; //used in next while loop
// this while loop will read in the user input dateTime and use that to get the column from the PI server.
//if the date time is entered incorrectly it will tell the user to try to input the datetime again
while (i==0)
{
Console.WriteLine("Enter date, ex:16 Jun 8:30 AM 2008, Press enter when done"); //instruct the user in how to enter the date
string userInput = Console.ReadLine(); //read in the date the user enters
string format = "dd MMM h:mm tt yyyy"; //how the system will read the date entered
DateTime dateTime;
//if date is entered correctly, parse it, grab the parsed value dateTime and exit loop
if (DateTime.TryParseExact(userInput, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
i = 1; //set the flag to exit while loop
}
//if input is bad return "Date entered incorrectly and run the loop again
else
{
Console.WriteLine(badDate);
i=0; //set the flag to run the loop again
}
}
var del = ","; //used in next using statement
var SplitExpression = new Regex(#"(" + del + #")(?=(?:[^""]|""[^""]*"")*$)"); //used in next using statement
//Use the dateTime from the previous while loop and use it to add each point in "testpts.csv" to "Load Query Test.csv"
using (StreamReader tags = new StreamReader(#"D:\\testpts.csv"))
{
// string userInput = Console.ReadLine();
string format = "dd MMM h:mm tt yyyy";
DateTime.TryParseExact(userInput, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
lines = tags.ReadLine();
var columns1 = SplitExpression.Split(lines).Where(s => s != del).ToArray();
var point = PIPoint.FindPIPoint(piServer, lines);
var value = point.RecordedValue(dateTime);
string returnXml = string.Format(#"<value=""{0}"" />", value);
columns[15] = columns[15].Replace("0", returnXml); //column the point should be placed in (in Load Query Test.csv)
}
//if statement that will replace any extra 0 testpt values with column 13 values
if (columns[15].Contains("0"))
{
columns[15] = columns[15].Replace("0", columns[13]);
}
writer.WriteLine(string.Join(delimiter, columns));
}
}
File.Delete(sourcePath); //delete the original csv
File.Move(tempPath, sourcePath); //replace the old csv with edited one
Console.ReadLine();
I'm getting the error in the using statement:
using (StreamReader tags = new StreamReader(#"D:\\testpts.csv"))
{
// string userInput = Console.ReadLine();
string format = "dd MMM h:mm tt yyyy";
DateTime.TryParseExact(userInput, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime);
lines = tags.ReadLine();
var columns1 = SplitExpression.Split(lines).Where(s => s != del).ToArray();
var point = PIPoint.FindPIPoint(piServer, lines);
var value = point.RecordedValue(dateTime);
string returnXml = string.Format(#"<value=""{0}"" />", value);
columns[15] = columns[15].Replace("0", returnXml); //column the point should be placed in (in Load Query Test.csv)
}
In this case the dateTime and userInput values are obviously out of context. I need them created in the previous while loop however because I want the user to be able to enter the correct date only once and ensure that it is entered correctly to make sure the script will actually pull data.
Please let me know if there is another way I can order my code or how I can make userInput and dateTime global. Thank you
Your problem lies in the "dateTime" variable. "userInput" is fine, the inner using statement has access to the scope of its outer using statement, because the inner one is part of the outer's scope.
The problem is with "dateTime" - the variable is declared inside a while loop, and there is a using block afterwards - after the variable is not available anymore, because the scope was disposed - which references a non existent variable.
Solution: move the declaration of your dateTime variable out of the while. Say, a line before the while's definition.
Without critisizing your code to much ... here an answer. You should be able to walk yourself from here on
Split the declaration of the variable with it's assignment
string userInput = Console.ReadLine();
to
string userInput;
userInput = Console.ReadLine();
Move the declarations (the first line) outside of the outer Loop.
Edit: Please, also have a look at Properties (you may call them
globals)
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]);