Date time value parsing for specific format C# - c#

There is a string 2020-12-27 20:00:00. An application must parse it to DateTime structure. Expected format is yyyy-MM-dd hh:mm:ss.
I use:
DateTime.TryParseExact(timeString, "yyyy-MM-dd hh:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out time)
but it doesn't work. TryParseExact returns false.
Anyone knows why?

You need to use HH instead of hh specifier.
HH specifier is for 24-hour clock format (00 to 23) but hh specifier is for 12-hour clock format (01 to 12).
string s = "2020-12-27 20:00:00";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// 27.12.2020 20:00:00
}

hh is 12 hours format, you should use HH for 24 hours
So your example becomes:
DateTime.TryParseExact(timeString, "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out time)

You can use method I wrote for purpose of converting DTs from string of any format:
public static DateTime? parseDate(this string date, string format = #"ddMMyyyy")
{
format += "HHmmss";
DateTime dt;
try
{
string day = date.Substring(format.IndexOf('d'), 2);
string month = date.Substring(format.IndexOf('M'), 2);
string year = date.Substring(format.IndexOf('y'), 4);
string hour = date.Length - 1 > format.IndexOf('H')? date.Substring(format.IndexOf('H'), 2) : "00";
string minute = date.Length - 1 > format.IndexOf('m')? date.Substring(format.IndexOf('m'), 2) : "00";
string second = date.Length - 1 > format.IndexOf('s')? date.Substring(format.IndexOf('s'), 2) : "00";
dt = DateTime.Parse(year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second);
}
catch { return null; }
return dt;
}
Usage:
string date = "2014ASDA04QWER05zxc";
DateTime? dt = date.parseDate("yyyyxxxxMMxxxxdd");
Result: 2014/04/05 00:00
However you are right maybe you should just use DateTime.ParseExact with HH instead of hh as my method is overcomplicated for this.
Little comparison of two methods using 20 000 random dates:

Related

Set am or pm String to Date Time Format in c#?

I have
int year=2017;
int month=02;
int day=01;
int hour=11;
int minutes=30;
String format="AM";
DateTime datetime=new DateTime(year,month,day,hour,minutes,0);
So how can i add this AM or PM format string to datetime?
One way is to use a condition:
int year = 2017;
int month = 2;
int day = 1;
int hour = 11;
int minutes = 30;
String format = "AM";
DateTime datetime = new DateTime(year,
month,
day,
(format.ToUpperInvariant() == "PM" && hour < 12) ?
hour + 12 : hour,
minutes,
00);
You can do it in the following way:
dateTime.ToString("yyyy-MM-dd hh:mm tt");
Its the 'tt' that adds the am/pm. Take a look at the MSDN docs (https://msdn.microsoft.com/en-us/library/zdtaw1bw%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396)
The answer is here: Convert to DateTime with AM/PM
DateTime.ParseExact("2/22/2015 9:54:02 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
In your case:
int year=2017;
int month=02;
int day=01;
int hour=11;
int minutes=30;
String format="AM";
DateTime datetime = DateTime.ParseExact($"{month}/{day}/{year} {hour}:{minutes}:00 {format}",
"M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

calculate difference between two dates using c#

I'm trying to calculate difference between two dates, my code is given below
DateTime daterenew = DateTime.Parse(drow.ItemArray.GetValue(16).ToString()); //18/01/2017
DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";
But I'm getting an error
"String was not recognized as a valid DateTime."
I would simplify that:
var daterenew = DateTime.ParseExact("18/01/2017", "dd/MM/yyyy", CultureInfo.InvariantCulture);
var res = ((daterenew - DateTime.Today).Days) + " Day(s) remains";
Note, that DateTime.Now != DateTime.Today.
Try something like this
string dateString = drow.ItemArray.GetValue(16).ToString();
DateTime daterenew = DateTime.ParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
renewstatuslbl.Text = string.Format("{0} Day(s) remains", (daterenew - DateTime.Now).TotalDays);
Idea is in ParseExact where you can set up format for your date in drow.ItemArray
Also look at TotalDays
Assuming your drow.ItemArray.GetValue(16).ToString()format is always dd/MM/yyyy. Use ParseExact
DateTime daterenew = DateTime.ParseExact(drow.ItemArray.GetValue(16).ToString(), "dd/MM/yyyy", null); //18/01/2017
//DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
DateTime datecurrent = DateTime.Now;
renewstatuslbl.Text = ((daterenew - datecurrent).Days) + " Day(s) remains";
The format of the date , causes the error. 18/01/2017
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
example I used "yyyy/MM/dd"
//DateTime daterenew = DateTime.Parse("18/01/2017"); //18/01/2017
DateTime daterenew = DateTime.Parse("2017.01.18"); //18/01/2017
DateTime datecurrent = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy"));
object renewstatuslbl = ((daterenew - datecurrent).Days) + " Day(s) remains";
thus, I think you can change the string date format first of the value before inserting to drow.ItemArray
enter codenamespace FineCalculation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DateTime date01 = date1.Value;
DateTime date02 = date2.Value;
TimeSpan timeSpan = date02 - date01;
int days = Convert.ToInt16(timeSpan.TotalDays);
double fine = 0;
if(days < 30)
{
fine = days * 0.5;
}else if(days > 30 && days < 60)
{
fine = days * 0.5 * 0.75;
}else if(days > 60)
{
fine = days * 0.5 * 0.75 * 1;
}
MessageBox.Show("For "+ days + " days fine is " + fine.ToString());
}
}
} here

convert standard date to standard persian date in c#

I have a function that can convert the standard date to persian standard date as you can see here:
public string ConvertToPersianToShow(DateTime datetime)
{
PersianCalendar persian_date = new PersianCalendar();
string date;
string year = Convert.ToString(persian_date.GetYear(datetime));
string Month = Convert.ToString(persian_date.GetMonth(datetime));
string day = Convert.ToString(persian_date.GetDayOfMonth(datetime));
date = year+"/" + Month + "/" + day;
return date;
}
But i have a problem with these outputs:
1394/5/1
1394/12/8
1395/7/12
These outputs should be like this :
1394/05/01
1394/12/08
1395/07/12
I can count the digit numbers of the day and month but i thing it isn't the best way to do that .could you please give me some help about how can i change these kind of outputs using stringformat?
All you need to do is add a leading zero. .ToString can be used.
string Month = persian_date.GetMonth(datetime).ToString("D2");
string day = persian_date.GetDayOfMonth(datetime).ToString("D2");
You can use this function:
private static string UpdateDate(string date)
{
date.PadLeft(2, '0');
}
date = year+"/" + UpdateDate(Month) + "/" + UpdateDate(day);

Rounding up a time to the nearest hour

ok basically I have a program that is re-writing text files and formatting them through various conditions, one of the conditions is that the date and time values in my original text file needs to be removed from its current location and moved into a new column I have created, this is done with the code below. I used a regex to find the date and time format and then remove it from its current location and store the value in a variable that I can use later...
if (line.Contains(date))
{
string pattern = #"(\d{2}:\d{2}:\d{2}\s?\d{2}/\d{2}/\d{4})";
string input = line;
string replacement = "";
Regex rgx = new Regex(pattern);
date1 = rgx.Match(input).ToString();
string result = rgx.Replace(input, replacement);
line = result;
}
This new value that is returned gets both the time and date values but only as one string, so I then used a split (shown below) to get the two values separate, now split[0] is my time variable (00/00/00 format) - which I now need to round up to the nearest hour. I am really not sure how to go about this, any ideas ?
string[] split = date1.Split(' ');
writer.WriteLine(split[0] + "\t" + split[1] + "\t" + line);
Get that date from the string into a DateTime struct. See for example the TryParseExact method
Then you can create a new DateTime value, based on year/month/day/hour of the value from the previous step, setting the minute and second parts to zero (see here )
Add one hour if the minutes or seconds part (of your first value) is not zero, using .AddHours(1), which returns a new DateTime value.
EDIT
Some sample code:
string inputdate = "2:56:30 8/7/2014";
DateTime dt;
System.Globalization.CultureInfo enUS = new System.Globalization.CultureInfo("en-US");
if (DateTime.TryParseExact(inputdate, "H:m:s d/M/yyyy", // hours:minutes:seconds day/month/year
enUS, System.Globalization.DateTimeStyles.None, out dt))
{
// 'dt' contains the parsed date: "8-7-2014 02:56:30"
DateTime rounded = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0);
if (dt.Minute > 0 || dt.Second > 0) // or just check dt.Minute >= 30 for regular rounding
rounded = rounded.AddHours(1);
// 'rounded' now contains the date rounded up: "8-7-2014 03:00:00"
}
else
{
// not a correct date
}
In my case, I need to round it to lower hour, and I used this logic:
DateTime x = new DateTime();
x = x.Date.AddHours(x.Hour);
You can try one liner solution to convert your DateTime to nearest hour,
//Input DateTime
DateTime input = DateTime.ParseExact("28/05/2021 2:16 PM", "dd/MM/yyyy h:mm tt", CultureInfo.InvariantCulture);
//Ternary Operation
var output = input.Minute > 30 //Check if mins are greater than 30
? input.AddHours(1).AddMinutes(-input.Minute) //if yes, then add one hour and set mins to zero
: input.AddMinutes(-input.Minute); //otherwise set mins to zero
Console.WriteLine(result.ToString());
Try Online: .NET Fiddle
Can you convert the string to a datetime?
Something like:
dateVariable = Convert.ToDateTime(dateString);
int hour = dateVariable.Hour;
int minute = dateVariable.Minute;
And then do the rounding.
Now as you have
string[] str = split[1].Split('/');
// create a new DateTime
int minutes = int.Parse(str[1]);
if(minutes >= 30)
hour = int.Parse(str[0]) + 1 // make sure if it 13 or 25 make it 1
minutes = 0 ;
sec = 0;
else {
hour = int.Parse(str[0]);
minutes = 0 ;
sec = 0 ;
}
var myDate = new Date(Year, month , day , hour , minutes , sec);
In C#
var Now = DateTime.Now;
var Nearest = Now.Date;
Nearest = Nearest.AddHours(Now.Hour + (Now.Minute >= 30 ? 1 : 0));
Now = Current time
Nearest = Rounded to the nearest hour

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

I have a need to convert a string value in the form "YYYYMMDDHHMMSS" to a DateTime. But not sure on how, may be a DateTime.Tryparse can be used to make this happen. Or is there any other way to do it. I can do this using some string operations to take "YYYYMMDD" alone, convert to a datetime and then add HH, MM, SS separately to that DateTime. But is there any DateTime.TryParse() methods that I can use in one line to convert a "YYYYMMDDHHMMSS" format string value to a DateTime value?
Define your own parse format string to use.
string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
In case you got a datetime having milliseconds, use the following formatString
string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);
Thanks
You have to use a custom parsing string. I also suggest to include the invariant culture to identify that this format does not relate to any culture. Plus, it will prevent a warning in some code analysis tools.
var date = DateTime.ParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
class Program
{
static void Main(string[] args)
{
int transactionDate = 20201010;
int? transactionTime = 210000;
var agreementDate = DateTime.Today;
var previousDate = agreementDate.AddDays(-1);
var agreementHour = 22;
var agreementMinute = 0;
var agreementSecond = 0;
var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);
DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));
Console.WriteLine("Selected Date : " + selectedDate.ToString());
Console.WriteLine("Start Date : " + startDate.ToString());
Console.WriteLine("End Date : " + endDate.ToString());
if (selectedDate > startDate && selectedDate <= endDate)
Console.WriteLine("Between two dates..");
else if (selectedDate <= startDate)
Console.WriteLine("Less than or equal to the start date!");
else if (selectedDate > endDate)
Console.WriteLine("Greater than end date!");
else
Console.WriteLine("Out of date ranges!");
}
}

Categories

Resources