How Can I get Today's date with UFTC stamp in c#? - c#

Is there an inbuild DateTime functionality that could give me a string format of today's date as 2020-12-22T13:36:45 Etc/UTC (+00)
I can think of these ways:
var date = DateTime.Now;
var result = date.ToString("yyyy-MM-ddTHH:mm:ss") + " Etc/UTC (+00)";
Console.WriteLine(date.ToString("yyyy-MM-ddTHH:mm:ss Etc/UTC (+00)"));
//Gives '2020-12-23T10:59:59 EAc/UTC (+00)' - incorrect t replaced by A
Console.WriteLine(result);
//Gives '2020-12-23T10:59:59 Etc/UTC (+00)' Correct,
As you can see I can get the correct format, though I am not sure this is the best solution, as it looks very artificial.
Is there a better way to format the string?

how about date.ToString("yyyy-MM-ddTHH:mm:ss 'Etc/UTC (+00)'")
or if you need the real timezone, date.ToString("yyyy-MM-ddTHH:mm:ss 'Etc/UTC ('zzz')'")

Related

C# DateTime Not Formatting Correctly to String

I am trying to get the created date and time of a particular file and then format it from 4/9/2016 to 040916. I end up with the result of 56DD16. I am not entirely sure where this value is coming from. I have used this method to format dates before without any problem. The code is below:
FileInfo fi = new FileInfo(Path.Combine(r.getCompanyFilesLocation(), r.getNyseFileName()));
DateTime dateCreated = fi.CreationTime;
string archiveFileName = dateCreated.ToString("mmDDyy");
You are using incorrect format string,mm Represent the Minute and there is nothing for DD, dd stands for day. so Change your formatString as MMddyy. to get the expected output. Here you can find more formatting options
string archiveFileName = dateCreated.ToString("MMddyy");
.ToString("mmDDyy") is incorrect. The format should be .ToString("MMddyy")
You can always review the Custom Date and Time Format Strings.
You were using wrong format. Use this one and you will get the exact same output you required:
DateTime dateCreated = fi.CreationTime;
string archiveFileName = dateCreated.ToString("MMddyy", CultureInfo.InvariantCulture);

DateTime.Parse - changes format

I'll try to illustrate an example:
var dateNow = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
produces: 10/01/2014 21:50:34
var dateNowParse = DateTime.Parse(DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
produces: 10/01/2014 9:50:34 PM
QUESTION:
How to parse the date, and keep formatting like: dd/MM/yyyy HH:mm:ss, with an 24 hour format, without any PM
Thank you!
Update 1
Sorry maybe my question wasn't so clear, i'll try to explain the real situation below.
Please do not focus on real meaning of DateTime.Now, suppose we have a string variable in the format of 10/01/2014 21:50:34, and then I try to parse it, and store the result in another variable. What I am willing to achieve is to keep the result in a DateTime variable which has the exact formatting 10/01/2014 21:50:34.
Now here is a snippet:
var stringDate = "10/01/2014 22:50:30";
DateTime parsedDate = DateTime.Parse(stringDate, CultureInfo.InvariantCulture);
//parsedDate result is: 10/01/2014 10:50:30 PM
What is frustrating me is:
In the stringDate the 22:50 hour says that the string is formatted to the 24 hour clock. (the 12 clock format uses hours counter up to 12)
If I used 22:50, Isn't logically that the output should'nt use any AM PM and 12 hour format?
How to parse the date, and keep formatting
You need to keep the format alongside the DateTime if you want to. A DateTime does not have any concept of being in a particular format. The value of the DateTime returned by Parse isn't "10/01/2014 9:50:34 PM" - it's that particular date and time, but not a string representation.
You could have a type which maintains the two together - or if you always want to format in the same way, just specify that format explicitly when you format, without keeping it as data with the DateTime value.
Personally I would try to stick to DateTime.ParseExact where feasible, as I find it easier to predict what it will do - but it does depend on your input. If it's input with a particular format that you're expecting, ParseExact really is the way forward, potentially with the invariant culture to avoid any cultural differences.
I would store the date now as a date
DateTime dateNow = DateTime.Now;
then when you need to display it with that formatting
String strNow = dateNow.ToString("dd/MM/yyyy HH:mm:ss");
If you have a date coming in with a format say in a String variable strNow and want to put it in the DateTime I would make sure to catch format exceptions
DateTime dateNow;
try {
dateNow = DateTime.ParseExact(strNow, "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
}
catch (FormatException) {
//Log something or set a default date.
}
DateTime.ParseExact(DateTime, Format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);
for example:
DateTime.ParseExact(strNow, "dd/MM/yyyy HH:mm:ss", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite);

How to get yesterday's date in C#

I want to retrieve yesterday's date in my ASP.NET web application using C#.
I've tried searching for a solution but have not had much success. The code I'm using just outputs today's date:
string yr = DateTime.Today.Year.ToString();
string mn = DateTime.Today.Month.ToString();
string dt = DateTime.Today.Day.ToString();
date = string.Format("{0}-{1}-{2}", yr, mn, dt);
How can I get yesterday's date?
Use DateTime.AddDays() method with value of -1
var yesterday = DateTime.Today.AddDays(-1);
That will give you : {6/28/2012 12:00:00 AM}
You can also use
DateTime.Now.AddDays(-1)
That will give you previous date with the current time e.g. {6/28/2012 10:30:32 AM}
The code you posted is wrong.
You shouldn't make multiple calls to DateTime.Today. If you happen to run that code just as the date changes you could get completely wrong results. For example if you ran it on December 31st 2011 you might get "2011-1-1".
Use a single call to DateTime.Today then use ToString with an appropriate format string to format the date as you desire.
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You don't need to call DateTime.Today multiple times, just use it single time and format the date object in your desire format.. like that
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
OR
string result = DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
You will get yesterday date by this following code snippet.
DateTime dtYesterday = DateTime.Now.Date.AddDays(-1);
var yesterday = DateTime.Now.AddDays(-1);
Something like this should work
var yesterday = DateTime.Now.Date.AddDays(-1);
DateTime.Now gives you the current date and time.
If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.
Finally .AddDays(-1) removes 1 day to give you yesterday.
string result = DateTime.Now.Date.AddDays(-1).ToString("yyyy-MM-dd");
DateTime dateTime = DateTime.Now ;
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");
The above snippet will work. It is also advisable to make single instance of DateTime.Now;
DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);
There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.
Also you can have a desirable format in the .ToString() version of the DateTime instance

How to validate if a "date and time" string only has a time?

I have a single string variable that stores what could be a full date or a partial date:
1) Full Date: 12/12/2010 12:33 AM
2) Partial Date: 12:33 AM (no date field only time)
I'm trying to figure out what would be the best approach to parse the string to figure out if the string is missing the date string or not. The reason is, in my code if the date is missing I will append a default date to the string (such as 1/1/1900). Keep in mind that the time could be in various formats.
Update - My particular answer to this problem.
As all the "posts" have stated, there are multiple answers to this problem, this is ultimately what I used and hope it can help others*:
public DateTime ProcessDateAndTime(string dateString)
{
string dateAndTimeString = dateString;
string[] timeFormats = new string[]
{
"hh:mm tt", "hh:mm:ss tt",
"h:mm tt", "h:mm:ss tt",
"HH:mm:ss", "HH:mm", "H:mm"
};
// check to see if the date string has a time only
DateTime dateTimeTemp;
if (DateTime.TryParseExact(dateString, timeFormats,
CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTimeTemp))
{
// setting date to 01/01/1900
dateAndTimeString = new DateTime(1900, 1, 1).ToShortDateString() + " " + dateString;
}
return DateTime.Parse(dateAndTimeString);
}
*Note: This method is based on the assumption that there are only a specific amount of time formats used in your application, and that it is guaranteed that a properly formatted date and time, or time only string passed in (pre-validation for removal of garbage text).
Use
Convert.ToDateTime(string value, IFormatProviderProvider provider)
Since the string comes in different flavors, provide different format providers as needed.
The order could be:
DateOnly
Time Only
DateTime
The convert will throw an format exception if it fails. If you prefer not to have exceptions, use Datetime.TryParse instead as that returns a boolean.
Depending on how the string is represented you could have more than 3 format providers.
You can try to validate string with a RegEx,
BTW, good regexes for DateTime validation can be found here
Here's one way to do this without knowing all possible time formats:
CultureInfo provider = CultureInfo.CurrentCulture;
DateTime time;
DateTime datetime;
bool isTime = DateTime.TryParse(dateString, provider, DateTimeStyles.NoCurrentDateDefault, out time)
&& time.Date == DateTime.MinValue.Date
&& DateTime.TryParse(dateString, provider, DateTimeStyles.None, out datetime)
&& datetime.Date != DateTime.MinValue.Date);
If the string only has a time then the first TryParse will set the date part to 1/1/0001 or DateTime.MinValue.Date and the second TryParse will set the date part to the current date. This will work unless it is run by Doctor Who after travelling back in time to 1/1/0001.
You can use DateTime.TryParseExact.
This might not be the best but it answers your question:
string dateString = "9:53AM";
if (!dateString.Contains('/')))
{
dateString = DateTime.Now.ToShortDateString() + " " + dateString;
}
Looking at the length of the string will be straight-forward and will support multiple formats. A string with a date and time will most certainly be longer than a string with just a time. However, if your input may have times with high precision (12:30:30:50:20 vs 12/11/11 12:30) and low precision this won't work.
This solution is ideal if you don't need to know the value in the string immediately, and only want to add the default date.
If you support times to the second, for instance, a time will have 8 or less characters and a date-time will have 9 or more.
Given that the time can be in various formats (12/24?) it would be best to user several patterns, in some pre-defined order, trying to parse with each and resolving when the first succeeds.
You can also try
DateTime aTime;
if (DateTime.TryParse(dateString, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.NoCurrentDateDefault, out aTime))
{
//if the there is no date part in the dateString, date will
// default to Gregorian 1/1/0001
}

String was not recognized as a valid DateTime " format dd/MM/yyyy"

I am trying to convert my string formatted value to date type with format dd/MM/yyyy.
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
What is the problem ?
It has a second override which asks for IFormatProvider. What is this? Do I need to pass this also? If Yes how to use it for this case?
Edit
What are the differences between Parse and ParseExact?
Edit 2
Both answers of Slaks and Sam are working for me, currently user is giving the input but this will be assured by me that they are valid by using maskTextbox.
Which answer is better considering all aspects like type saftey, performance or something you feel like
Use DateTime.ParseExact.
this.Text="22/11/2009";
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", null);
You need to call ParseExact, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.
Parsing a string representation of a DateTime is a tricky thing because different cultures have different date formats. .Net is aware of these date formats and pulls them from your current culture (System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat) when you call DateTime.Parse(this.Text);
For example, the string "22/11/2009" does not match the ShortDatePattern for the United States (en-US) but it does match for France (fr-FR).
Now, you can either call DateTime.ParseExact and pass in the exact format string that you're expecting, or you can pass in an appropriate culture to DateTime.Parse to parse the date.
For example, this will parse your date correctly:
DateTime.Parse( "22/11/2009", CultureInfo.CreateSpecificCulture("fr-FR") );
Of course, you shouldn't just randomly pick France, but something appropriate to your needs.
What you need to figure out is what System.Threading.Thread.CurrentThread.CurrentCulture is set to, and if/why it differs from what you expect.
Although the above solutions are effective, you can also modify the webconfig file with the following...
<configuration>
<system.web>
<globalization culture="en-GB"/>
</system.web>
</configuration>
Ref : Datetime format different on local machine compared to production machine
You might need to specify the culture for that specific date format as in:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); //dd/MM/yyyy
this.Text="22/11/2009";
DateTime date = DateTime.Parse(this.Text);
For more details go here:
http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Based on this reference, the next approach worked for me:
// e.g. format = "dd/MM/yyyy", dateString = "10/07/2017"
var formatInfo = new DateTimeFormatInfo()
{
ShortDatePattern = format
};
date = Convert.ToDateTime(dateString, formatInfo);
After spending lot of time I have solved the problem
string strDate = PreocessDate(data);
string[] dateString = strDate.Split('/');
DateTime enter_date = Convert.ToDateTime(dateString[1]+"/"+dateString[0]+"/"+dateString[2]);
private DateTime ConvertToDateTime(string strDateTime)
{
DateTime dtFinaldate; string sDateTime;
try { dtFinaldate = Convert.ToDateTime(strDateTime); }
catch (Exception e)
{
string[] sDate = strDateTime.Split('/');
sDateTime = sDate[1] + '/' + sDate[0] + '/' + sDate[2];
dtFinaldate = Convert.ToDateTime(sDateTime);
}
return dtFinaldate;
}
use this to convert string to datetime:
Datetime DT = DateTime.ParseExact(STRDATE,"dd/MM/yyyy",System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat)
Just like someone above said you can send it as a string parameter but it must have this format: '20130121' for example and you can convert it to that format taking it directly from the control. So you'll get it for example from a textbox like:
date = datetextbox.text; // date is going to be something like: "2013-01-21 12:00:00am"
to convert it to: '20130121' you use:
date = date.Substring(6, 4) + date.Substring(3, 2) + date.Substring(0, 2);
so that SQL can convert it and put it into your database.
Worked for me below code:
DateTime date = DateTime.Parse(this.Text, CultureInfo.CreateSpecificCulture("fr-FR"));
Namespace
using System.Globalization;
You can use also
this.Text = "22112009";
DateTime newDateTime = new DateTime(Convert.ToInt32(this.Text.Substring(4, 4)), // Year
Convert.ToInt32(this.Text.Substring(2,2)), // Month
Convert.ToInt32(this.Text.Substring(0,2)));// Day
Also I noticed sometimes if your string has empty space in front or end or any other junk char attached in DateTime value then also we get this error message

Categories

Resources