Convert Timeformat to normal datetime - c#

I have to convert this time format string (20130221191038.576375+330) to normal datetime through c# classes like datetime.
please share the idea to convert this..

Thanks guys, I got the solution for my requirement with the help of Erik,tung and BlackHatShadow.
Referred this
this also

The format you have is a CIM_DATETIME value, which is almost simple to parse. The only problem is that it specifies the timezone as an offset in number of minutes.
You can use the DateTime.TryParseExact to convert the portion of the string prior to the timezone specifier, then subtract the timezone value (in minutes) from the result to get the UTC datetime. Then you can convert to local time if you need, or leave it in UTC form.
public static DateTime? CIMToUTCDateTime(string CIM_DATETIME)
{
// CIM_DATETIME must be 25 characters in length
if (string.IsNullOrEmpty(CIM_DATETIME) || CIM_DATETIME.Length != 25)
return null;
// Get the datetime portion of the string without timezone offset
string dtPortion = CIM_DATETIME.Substring(0, 21);
// convert to datetime
DateTime dt;
if (!DateTime.TryParseExact(dtPortion, "yyyyMMddHHmmss.ffffff", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.AssumeUniversal | System.Globalization.DateTimeStyles.AdjustToUniversal, out dt))
return null;
// subtract timezone offset to get UTC time equivalent
int tzoffset;
if (!Int32.TryParse(CIM_DATETIME.Substring(21), out tzoffset))
return null;
dt = dt.AddMinutes(-tzoffset);
// return UTC datetime
return dt;
}
And now that I've written this horrid little method, you've gone and found another solution. Typical :P

I know you already found a solution, but I came across this nice ManagementDateTimeConverter .Net class that does exactly what you want. All you need to do is:
// This gets converted to your local time
DateTime converted = ManagementDateTimeConverter.ToDateTime("20130221191038.576375+330")
// If you want the UTC equivalent:
converted.ToUniversalTime()

Related

Parse year/month/day string with unknown dividers and optional time element into a DateTime, in C#

I have to parse date string in C#. The dates are all ensured to start with year, month, day. But I do not know what dividers will be between the 3 parts.
Additionally the date string may also include a time part after the date.
Basically as long as the format has the year first, month second, and day third, I should parse it as a valid date regardless of which dividers are used and whether a time is included. Any other date formats should be rejected as invalid.
I can not figure out how to do this without writing a long if/else.
How do I parse a string into a C# datetime object, given the restrictions mentioned?
You can check the length of the input string is at least 10 characters, and if it is, work out what the separator should be by looking at the 5th character in the string.
Then you can use the separator to construct a format string that you pass to DateTime.TryParseExact() to parse the date. You also have to truncate the date string to 10 characters to ignore any date part at the end.
An example implementation looks like this - it returns null if the date didn't parse; otherwise, it returns the correctly parsed date:
public static DateTime? ParseDateWithUnknownDivider(string dateStr)
{
if (dateStr.Length < 10)
return null;
char divider = dateStr[4];
if (DateTime.TryParseExact(
dateStr.Substring(0, 10),
$"yyyy\\{divider}MM\\{divider}dd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out DateTime result))
return result;
return null;
}
Note that this ignores the time part and will always return the time part as 00:00:00. If that's not what you meant, you will need to specify in your question what the time part would look like. For example, would it be separated from the date part by a space? And would it always be hh:mm:ss? And would it be 24hour clock?
try this code
string yourDateTimeString = ....;
string format="yyyy/MM/dd";
var dt = DateTime.ParseExact(yourDateTimeString,format,null,System.Globalization.DateTimeStyles.AssumeLocal);

How to set timezone based timestamp to get current date and time in C#? [duplicate]

This code has been working for a long time now but has broken now when I try to pass DateTime.Now as the outageEndDate parameter:
public Outage(DateTime outageStartDate, DateTime outageEndDate, Dictionary<string, string> weeklyHours, string province, string localProvince)
{
this.outageStartDate = outageStartDate;
this.outageEndDate = outageEndDate;
this.weeklyHours = weeklyHours;
this.province = province;
localTime = TimeZoneInfo.FindSystemTimeZoneById(timeZones[localProvince]);
if (outageStartDate < outageEndDate)
{
TimeZoneInfo remoteTime = TimeZoneInfo.FindSystemTimeZoneById(timeZones[province]);
outageStartDate = TimeZoneInfo.ConvertTime(outageStartDate, localTime, remoteTime);
outageEndDate = TimeZoneInfo.ConvertTime(outageEndDate, localTime, remoteTime);
The error message I am getting on the last line is that the Kind property is not set correctly on the DateTime parameter (outageEndDate). I've Googled and checked SO for examples but I don't really understand the error message.
Any advice is appreciated.
Regards.
EDIT - The exact error message is:
The conversion could not be completed because the supplied DateTime did not have the Kind
property set correctly. For example, when the Kind property is DateTimeKind.Local, the source
time zone must be TimeZoneInfo.Local. Parameter name: sourceTimeZone
EDIT: outageEndDate.Kind = Utc
Thanks for clarifying your question.
If the DateTime instance Kind is Local, then TimeZoneInfo.ConvertTime will expect the second parameter to be the local timezone of your computer.
If DateTime instance Kind is Utc, then TimeZoneInfo.ConvertTime will expect the second parameter to be the Utc timezone.
You need to convert outageEndDate to the right timezone first, just in case the localProvice timezone doesn't match the timezone on your computer.
outageEndDate = TimeZoneInfo.ConvertTime(outageEndDate, localTime);
here is an example of something that you could try
It depends on what you mean by "a GMT + 1 timezone". Do you mean permanently UTC+1, or do you mean UTC+1 or UTC+2 depending on DST?
If you're using .NET 3.5, use TimeZoneInfo to get an appropriate time zone, then use:
// Store this statically somewhere
TimeZoneInfo maltaTimeZone = TimeZoneInfo.FindSystemTimeZoneById("...");
DateTime utc = DateTime.UtcNow;
DateTime malta = TimeZoneInfo.ConvertTimeFromUtc(utc, maltaTimeZone );
You'll need to work out the system ID for the Malta time zone, but you can do that easily by running this code locally:
Console.WriteLine(TimeZoneInfo.Local.Id);
If you're not using .NET 3.5, you'll need to work out the daylight savings yourself. To be honest, the easiest way to do that is going to be a simple lookup table. Work out the DST changes for the next few years, then write a simple method to return the offset at a particular UTC time with that list hardcoded. You might just want a sorted List<DateTime> with the known changes in, and alternate between 1 and 2 hours until your date is after the last change:
// Be very careful when building this list, and make sure they're UTC times!
private static readonly IEnumerable<DateTime> DstChanges = ...;
static DateTime ConvertToLocalTime(DateTime utc)
{
int hours = 1; // Or 2, depending on the first entry in your list
foreach (DateTime dstChange in DstChanges)
{
if (utc < dstChange)
{
return DateTime.SpecifyKind(utc.AddHours(hours), DateTimeKind.Local);
}
hours = 3 - hours; // Alternate between 1 and 2
}
throw new ArgumentOutOfRangeException("I don't have enough DST data!");
}

c# Is it possible to subtract a day in the datetime format

I have the following simple example:
string dt = DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss");
I can't change the DateTime.Now, but I can change datetime format yyyy-MM-dd hh.mm.ss. Following this example the result must be today's date, but I need to get yesterday's date with the same parameters except day (year, month, hours, minutes and seconds). E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it possible to use some "-" operator or something else inside the datetime format to achieve the result?
If you want yesterday's date, you can do this
string dt = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd hh.mm.ss");
DateTime.AddDays() lets you add number of days, positive for future date, negative for past date.
E.g. 2015-08-23 12.09.59 must be 2015-08-22 12.09.59. So is it
possible to use some "-" operator or something else inside the
datetime format to achieve the result?
No, it's not possible inside the DateTime format. you can not change any thing. Because it is only for define format of the Date to display in string format. Any addition or subtraction can only be done before converting it to string format as suggested by "Arghya C".
Can you explain your limitation so we can solve your problem.
If you can only influence the date time pattern, than use the roundtrip format and parse the returning string back to a date time, add the calculation and format it into the desired format:
var dateTimeString = badLibrary.GetDateTime("o");
var dateTime = DateTime.Parse(dateTimeString, null, DateTimeStyles.RoundtripKind);
var newDateTime = dateTime.AddDays(-1);
return newDateTime.ToString("yyyy-MM-dd hh.mm.ss");

How to get today's date in mm/dd/yyyy format into a datetime variable in c#

I want today's date in mm/dd/yyyy format from a DateTime variable. How to get it?
I need to check this with some date variable so it must be also in date variable format?plz help
Ex: i need to get today date in mm/dd/yyyy format and i already date which is datetime datatype in mm/dd/yyyy format and i have to compare them
You should use DateTime.Today:
DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("MM/dd/yyyy"); // As String
Edit: You edited your post to add another question, so here comes my edit to supply at least some sort of answer.
Update While you can use DateTime.Compare() you should use plain comparisson:
if(today < otherdate)
{
// Do something.
}
Alternatively, you can use DateTime-variables to check against other DateTime-variables using the DateTime.Compare() method. Both otpions will work and it comes down to preference and what you want to do with the result.
int result = DateTime.Compare(today, otherdate);
if(result < 0)
MessageBox.Show("Today is earlier than the 'otherdate'");
elseif(result > 0)
MessageBox.Show("Today is later than the 'other date'");
else
MessageBox.Show("Dates are equal...");
string datestring = DateTime.Now.ToString("MM/dd/yyyy");
MSDN say: Custom Date and Time Format Strings
To convert DateTime variable to string in the specified format:
DateTime d = ...;
string s = d.ToString("MM/dd/yyyy");
If you want to compare only date part of DateTime, not time part:
DateTime d1 = DateTime.Parse("10/10/2011");
DateTime d2 = DateTime.Parse("01/01/2011");
if (d1.Date > d2.Date)
{
// do the stuff
}
DateTime.Now.ToString("MM/dd/yyyy");
DateTime.Today.ToString("MM/dd/yyyy");
DateTime.Parse is what you are looking for...

convert string to date without time

This line
System.DateTime.Parse("09/12/2009");
convert date (string) to 9/12/2009 12:00:00 AM. How can I get a date in the form 9/12/2009.
after explanations I do:
DateTime dt = System.DateTime.Parse(Request.Form["datepicker"]);
dt.ToString("dd/mm/yyyy");
/* and this code have time, why???*/
Your problem is not with the parsing but with the output. Look at how ToString works for DateTime, or use this example:
using System;
class Program
{
static void Main(string[] args)
{
DateTime dt = DateTime.Parse("09/12/2009");
Console.WriteLine(dt.ToString("dd/MM/yyyy"));
}
}
Or to get something in your locale:
Console.WriteLine(dt.ToShortDateString());
Update: Your update to the question implies that you do not understand fully my answer yet, so I'll add a little more explanation. There is no Date in .NET - there is only DateTime. If you want to represent a date in .NET, you do so by storing the time midnight at the start of that day. The time must always be stored, even if you don't need it. You cannot remove it. The important point is that when you display this DateTime to a user, you only show them the Date part.
Anything parsed to a DateTime object will contain date+time. If no time is sepcified, the assumed value will be 0000hr.
To get the date-only representation, it's up to how you format it to string.
E.g. theDate.ToString("dd/MM/yyyy")
Refer to the MSDN Date and Time Format Strings.
if you want to convert gridview datetime column to date only column use this code :
raddgvDaybook.Rows.ToList().ForEach(x =>
{
DateTime dt = DateTime.Parse(x.Cells["Vocdate"].Value.ToString());
string str = string.Format("{0:MM/dd/yyyy}", dt);
x.Cells["Vocdate"].Value = str;
});
I tested the code it will work if you bind the datetime as string in dgv.

Categories