Convert Date as given in formation string - c#

I have a function that converts a given date to timestamp. the date format is dynamic. for example (it could be 'dd/MM/yyyy' or 'dd-MM-yyyy' or MM/dd/yyyy).but date format is also passed as an argument in the function. i need to seperate day , month and year for this conversion. how can i separate as given in formation string
public static double GetTimeStamp(string date, string format)
{
string[] dateToConvert = date.Split('/');
int year=Int32.Parse(dateToConvert[2]);
int month=Int32.Parse(dateToConvert[1]);
int day=Int32.Parse(dateToConvert[0]);
var baseDate = new DateTime(1970, 01, 01);
var toDate = new DateTime(year, month, day);
var numberOfSeconds = toDate.Subtract(baseDate).TotalSeconds;
return numberOfSeconds;
}
i am using '/' as a separation character. but i want to separate it as provided in the formation. if formation string is (dd-MM-yyyy). i need to seperate it using '-' charecter

DateTime dateTime = DateTime.ParseExact(date, format, null);
int year = dateTime.Year;
int month=dateTime.Month;
int day = dateTime.Day;
var toDate = new DateTime(year, month, day);

Related

How to convert a string to DateTime in a TextBox of a gridview [duplicate]

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?
Since you are handling 24-hour based time and you have a comma separating the seconds fraction, I recommend that you specify a custom format:
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
You have basically two options for this. DateTime.Parse() and DateTime.ParseExact().
The first is very forgiving in terms of syntax and will parse dates in many different formats. It is good for user input which may come in different formats.
ParseExact will allow you to specify the exact format of your date string to use for parsing. It is good to use this if your string is always in the same format. This way, you can easily detect any deviations from the expected data.
You can parse user input like this:
DateTime enteredDate = DateTime.Parse(enteredString);
If you have a specific format for the string, you should use the other method:
DateTime loadedDate = DateTime.ParseExact(loadedString, "d", null);
"d" stands for the short date pattern (see MSDN for more info) and null specifies that the current culture should be used for parsing the string.
try this
DateTime myDate = DateTime.Parse(dateString);
a better way would be this:
DateTime myDate;
if (!DateTime.TryParse(dateString, out myDate))
{
// handle parse failure
}
Use DateTime.Parse(string):
DateTime dateTime = DateTime.Parse(dateTimeStr);
Nobody seems to implemented an extension method. With the help of #CMS's answer:
Working and improved full source example is here: Gist Link
namespace ExtensionMethods {
using System;
using System.Globalization;
public static class DateTimeExtensions {
public static DateTime ToDateTime(this string s,
string format = "ddMMyyyy", string cultureString = "tr-TR") {
try {
var r = DateTime.ParseExact(
s: s,
format: format,
provider: CultureInfo.GetCultureInfo(cultureString));
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
public static DateTime ToDateTime(this string s,
string format, CultureInfo culture) {
try {
var r = DateTime.ParseExact(s: s, format: format,
provider: culture);
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
}
}
namespace SO {
using ExtensionMethods;
using System;
using System.Globalization;
class Program {
static void Main(string[] args) {
var mydate = "29021996";
var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}
mydate = "2016 3";
date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}
mydate = "2016 12";
date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}
mydate = "2016/31/05 13:33";
date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}
mydate = "2016/31 Ocak";
date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}
mydate = "2016/31 January";
date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US");
// {31.01.2016 00:00:00}
mydate = "11/شعبان/1437";
date = mydate.ToDateTime(
culture: CultureInfo.GetCultureInfo("ar-SA"),
format: "dd/MMMM/yyyy");
// Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*
System.Diagnostics.Debug.Assert(
date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
}
}
}
I tried various ways. What worked for me was this:
Convert.ToDateTime(data, CultureInfo.InvariantCulture);
data for me was times like this 9/24/2017 9:31:34 AM
Try the below, where strDate is your date in 'MM/dd/yyyy' format
var date = DateTime.Parse(strDate,new CultureInfo("en-US", true))
Convert.ToDateTime or DateTime.Parse
DateTime.Parse
Syntax:
DateTime.Parse(String value)
DateTime.Parse(String value, IFormatProvider provider)
DateTime.Parse(String value, IFormatProvider provider, DateTypeStyles styles)
Example:
string value = "1 January 2019";
CultureInfo provider = new CultureInfo("en-GB");
DateTime.Parse(value, provider, DateTimeStyles.NoCurrentDateDefault););
Value: string representation of date and time.
Provider: object which provides culture specific info.
Styles: formatting options that customize string parsing for some date and time parsing methods. For instance, AllowWhiteSpaces is a value which helps to ignore all spaces present in string while it parse.
It's also worth remembering DateTime is an object that is stored as number internally in the framework, Format only applies to it when you convert it back to string.
Parsing converting a string to the internal number type.
Formatting converting the internal numeric value to a readable
string.
I recently had an issue where I was trying to convert a DateTime to pass to Linq what I hadn't realised at the time was format is irrelevant when passing DateTime to a Linq Query.
DateTime SearchDate = DateTime.Parse(searchDate);
applicationsUsages = applicationsUsages.Where(x => DbFunctions.TruncateTime(x.dateApplicationSelected) == SearchDate.Date);
Full DateTime Documentation
string input;
DateTime db;
Console.WriteLine("Enter Date in this Format(YYYY-MM-DD): ");
input = Console.ReadLine();
db = Convert.ToDateTime(input);
//////// this methods convert string value to datetime
///////// in order to print date
Console.WriteLine("{0}-{1}-{2}",db.Year,db.Month,db.Day);
You could also use DateTime.TryParseExact() as below if you are unsure of the input value.
DateTime outputDateTimeValue;
if (DateTime.TryParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out outputDateTimeValue))
{
return outputDateTimeValue;
}
else
{
// Handle the fact that parse did not succeed
}
I just found an elegant way:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/شعبان/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
Put this code in a static class> public static class ClassName{ }
public static DateTime ToDateTime(this string datetime, char dateSpliter = '-', char timeSpliter = ':', char millisecondSpliter = ',')
{
try
{
datetime = datetime.Trim();
datetime = datetime.Replace(" ", " ");
string[] body = datetime.Split(' ');
string[] date = body[0].Split(dateSpliter);
int year = date[0].ToInt();
int month = date[1].ToInt();
int day = date[2].ToInt();
int hour = 0, minute = 0, second = 0, millisecond = 0;
if (body.Length == 2)
{
string[] tpart = body[1].Split(millisecondSpliter);
string[] time = tpart[0].Split(timeSpliter);
hour = time[0].ToInt();
minute = time[1].ToInt();
if (time.Length == 3) second = time[2].ToInt();
if (tpart.Length == 2) millisecond = tpart[1].ToInt();
}
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
catch
{
return new DateTime();
}
}
In this way, you can use
string datetime = "2009-05-08 14:40:52,531";
DateTime dt0 = datetime.TToDateTime();
DateTime dt1 = "2009-05-08 14:40:52,531".ToDateTime();
DateTime dt5 = "2009-05-08".ToDateTime();
DateTime dt2 = "2009/05/08 14:40:52".ToDateTime('/');
DateTime dt3 = "2009/05/08 14.40".ToDateTime('/', '.');
DateTime dt4 = "2009-05-08 14:40-531".ToDateTime('-', ':', '-');
String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);
this one gives you
2019-08-17 11:14:49.000
Different cultures in the world write date strings in different ways. For example, in the US 01/20/2008 is January 20th, 2008. In France this will throw an InvalidFormatException. This is because France reads date-times as Day/Month/Year, and in the US it is Month/Day/Year.
Consequently, a string like 20/01/2008 will parse to January 20th, 2008 in France, and then throw an InvalidFormatException in the US.
To determine your current culture settings, you can use System.Globalization.CultureInfo.CurrentCulture.
string dateTime = "01/08/2008 14:50:50.42";
DateTime dt = Convert.ToDateTime(dateTime);
Console.WriteLine("Year: {0}, Month: {1}, Day: {2}, Hour: {3}, Minute: {4}, Second: {5}, Millisecond: {6}",
dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, dt.Millisecond);
This worked for me:
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dt = DateTime.ParseExact("2009-05-08 14:40:52,531","yyyy-MM-dd HH:mm:ss,fff", provider);
Do you want it fast?
Let's say you have a date with format yyMMdd.
The fastest way to convert it that I found is:
var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000,
(s[2] - '0') * 10 + s[3] - '0',
(s[4] - '0') * 10 + s[5] - '0')
Just, choose the indexes according to your date format of choice. If you need speed probably you don't mind the 'non-generic' way of the function.
This method takes about 10% of the time required by:
var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);

How to get the day value out of a textbox in C#?

For example, if the textbox contains 11/11/2016 OR 01/05/2016
How to get the day value only? example. 11 OR 01
One way is to parse the string in the TextBox to DateTime using an exact format. Then using the DateTime object, you can extract the Day Property:
DateTime date;
bool success = DateTime.TryParseExact(textBoxDate.Text, "dd/MM/yyyy",
CultureInfo.CurrentCulture,
DateTimeStyles.AssumeLocal, out date);
int day;
if(success)
{
day = date.Day; // 1
// or string stringDay = date.ToString("dd"); to get 01
}
else
{
// handle error
}
Another way that I don't prefer (Not 100% safe input validation) is to use String.Split like this:
string strDay = textBoxDate.Text.Split('/').FirstOrDefault();
int day;
if(Int32.TryParse(strDay, out day))
{
// success
}
else
{
// Handle Error
}
string myString = textbox1.text;
DateTime day = DateTime.ParseExact(myString, "dd/MM/yyyy", CultureInfo.InvariantCulture);
int day = birthday.Day;

change persian date to gregorian date and vice versa

I used the following code in order to change Persian date to Gregorian date. for example it changes 1393/05/05 to 2014/05/26.
if (MultiView6.ActiveViewIndex == 1)
{
date = Convert.ToDateTime(txtDate.Text);
string change = date.ToString("yyyy/MM/dd");
int day1 = Convert.ToInt32(change.Substring(8, 2));
int mon1 = Convert.ToInt32(change.Substring(5, 2));
int year1 = Convert.ToInt32(change.Substring(0, 4));
PersianCalendar pc = new PersianCalendar();
change = (pc.ToDateTime(year1, mon1, day1, 0, 0, 0, 0).ToString("yyyy/MM/dd").Substring(0, 10));
date = Convert.ToDateTime(change);
}
however for some special dates such as 1393/02/29 the code stops working and I receive the above error from the first line of my code:
String was not recognized as a valid DateTime.
I suppose I would have the same problem if I want to convert 2014/05/19 to Persian date (which is 1393/02/29)....
is there a way to fix this error?
year, month and day are in PersianCalendar and you can't use them in DateTime. if you want to convert from PersianCalendar to DateTime, you have to do this:
DateTime d1=p.ToDateTime(year, month, day, 0, 0, 0, 0);
=====================================================
in your new code you have another mistake. variables day1, mon1 and year1 are in Gregorian calendar and you can't use them in PersianCalendar.ToDateTime().
All you need is to use constructor accepting Calendar - DateTime(int year, int month, int day, Calendar calendar).
string persianDateString = "1393/02/29";
string[] persianDateParts = persianDateString.Split('/');
int persianYear = int.Parse(persianDateParts[0]);
int persianMonth = int.Parse(persianDateParts[1]);
int persianDay = int.Parse(persianDateParts[2]);
PersianCalendar pc = new PersianCalendar();
DateTime date = new DateTime(persianYear, persianMonth, persianDay, pc);

c# months and years between given dates

I try to popup a msgbox that shows the months and years of the given dates for example
my input is:
7/2012 and 2/2013
and the output should be:
7/2012,8/2012,9/2012,10/2012,11/2012,12/2012,1/2013,2/2013
I wrote:
string datePart1;
string datePart2;
string[] date1 = new string[] { "" };
string[] date2 = new string[] { "" };
private void button1_Click(object sender, EventArgs e)
{
DateTime endDate = new DateTime(2013, 2, 1); // i will be having the date time as a variable from a textbox
DateTime begDate = new DateTime(2012, 7, 1); // i will be having the date time as a variable from a text box
int year, month;
if (endDate.Month - begDate.Month < 0)
{
month = (endDate.Month - begDate.Month) + 12;
endDate = new DateTime(endDate.Year - 1, endDate.Month, endDate.Day);
}
else
month = endDate.Month - begDate.Month;
year = endDate.Year - begDate.Year;
The above code calculates the time difference, but my attempts at outputting haven't worked.
Here's a sample to get you started.
It provides a handy MonthsInRange() method which returns a sequence of all the months in the specified range. You can then format the returned dates using "M\\/yyyy" (see below) to output the required format. (Note: That's not a letter V, it's a backslash followed by a forward slash!)
See Custom Date and Time Format Strings for an explanation of the format string.
using System;
using System.Collections.Generic;
namespace Demo
{
public static class Program
{
static void Main(string[] args)
{
DateTime endDate = new DateTime(2013, 2, 1);
DateTime begDate = new DateTime(2012, 7, 1);
foreach (DateTime date in MonthsInRange(begDate, endDate))
{
Console.WriteLine(date.ToString("M\\/yyyy"));
}
}
public static IEnumerable<DateTime> MonthsInRange(DateTime start, DateTime end)
{
for (DateTime date = start; date <= end; date = date.AddMonths(1))
{
yield return date;
}
}
}
}
Why "M\\/yyyy" and not just "M/yyyy"?
This is because the "/" character in a DateTime format string will be interpreted as the "date separator", not a literal "/". In some locales, this will come out as "." and not "/".
To fix this, we need to escape it with a "\" character. However, we can't just use a single "\" because C# itself will interpret that as an escape character, and will use it to escape the following character. The C# escape sequence for a literal "\" is "\\", which is why we have to put "\\/" and not just "\/".
Alternatively you can turn of escaping of "\" characters by prefixing the string with an # character, like so:
#"M/yyyy"
You can use whichever you prefer.
Since you're not guaranteed to have dates with the same day, you can use this code which creates new dates that only consider the first of the month.
static IEnumerable<string> InclusiveMonths(DateTime start, DateTime end)
{
// copies to ensure the same day.
var startMonth = new DateTime(start.Year, start.Month, 1);
var endMonth = new DateTime(end.Year, end.Month, 1);
for (var current = startMonth; current <= endMonth; current = current.AddMonths(1))
yield return current.ToString("M/yyyy");
}
// usage
foreach (var mmyyyy in InclusiveMonths(begDate, endDate))
{
Console.WriteLine(mmyyyy);
}
var allMonths = string.Join(", ", InclusiveMonths(begDate, endDate));
Look into using the TimeSpan structure, it'll help you achieve your goal a lot faster.
http://msdn.microsoft.com/en-us/library/system.timespan.aspx
You may use
TimeSpan dateDifference = endDate - begDate;
year = dateDifference.Days / 365;
month = dateDifference.Days / 30;
Edit:
I forgot TimeSpan does not feature Year or Month, sorry :(

What's the best way to produce a relative date range (This week, This year, Last month, etc) from a DateTime?

I'm sure I'm not the first person to need to do this, so I'm looking for the best way.
I've got a set of radio buttons with choices such as
This Year
Last Year
This Month
Last Month
This Week
Last Week
and I need to produce the proper relative date range from the current date (DateTime.Now).
For example if Last Year was selected and the current date was 4/2/09 14:45:32 I would need to return a start date of 1/1/08 00:00:00 and end date of 12/31/08 23:59:59.
Any thoughts?
All of these have been tested using DateTime.Today, and work just like you asked for:
public struct DateRange
{
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
public static DateRange ThisYear(DateTime date)
{
DateRange range = new DateRange();
range.Start = new DateTime(date.Year, 1, 1);
range.End = range.Start.AddYears(1).AddSeconds(-1);
return range;
}
public static DateRange LastYear(DateTime date)
{
DateRange range = new DateRange();
range.Start = new DateTime(date.Year - 1, 1, 1);
range.End = range.Start.AddYears(1).AddSeconds(-1);
return range;
}
public static DateRange ThisMonth(DateTime date)
{
DateRange range = new DateRange();
range.Start = new DateTime(date.Year, date.Month, 1);
range.End = range.Start.AddMonths(1).AddSeconds(-1);
return range;
}
public static DateRange LastMonth(DateTime date)
{
DateRange range = new DateRange();
range.Start = (new DateTime(date.Year, date.Month, 1)).AddMonths(-1);
range.End = range.Start.AddMonths(1).AddSeconds(-1);
return range;
}
public static DateRange ThisWeek(DateTime date)
{
DateRange range = new DateRange();
range.Start = date.Date.AddDays(-(int)date.DayOfWeek);
range.End = range.Start.AddDays(7).AddSeconds(-1);
return range;
}
public static DateRange LastWeek(DateTime date)
{
DateRange range = ThisWeek(date);
range.Start = range.Start.AddDays(-7);
range.End = range.End.AddDays(-7);
return range;
}
This year:
DateTime Today = DateTime.Today;
DateTime StartDate = new DateTime(Today.Year,1,1);
DateTime EndDate = StartDate.AddYears(1).AddSeconds(-1);
This month:
DateTime Today = DateTime.Today;
DateTime StartDate = new DateTime(Today.Year,Today.Month,1);
DateTime EndDate = StartDate.AddMonths(1).AddSeconds(-1);
This week:
DateTime Today = DateTime.Today;
DateTime StartDate = Today.AddDays(-((int) Today.DayOfWeek));
DateTime EndDate = StartDate.AddDays(7).AddSeconds(-1);
Last year / month / week are simple variations on above. Edit: This week assumes the week starts on Sunday. You would have to modify the code slightly if your weeks start on Monday.
I would create a factory method which will return an interface (or a delegate which you can execute) which would be passed the current date and return the date range for you based on the implementation.
Of course, which implementation you return from the factory method would be determined by the value of an enumeration you pass to it which corresponds to "this year", "last year", etc, etc.
I would use the DateTime built-in methods for Adding and returning specific portions of the date to write a function that would return the interval.

Categories