How to store convert date time in int? - c#

I need to store DateTime in int. So I tried below codes
Int64 n = Int64.Parse(DateTime.Today.ToString("dd-MM-yyyy"));
or
Int64 twoday_date=Convert.ToInt64(System.DateTime.Today.ToString("dd-MM-yyyy"));
but its showing error:
Input string was not in a correct format.
Where is the error?

Just use DateTime.Ticks instead - there's absolutely no reason to start converting to and from strings here.
long ticks = DateTime.Today.Ticks;
// Later in the code when you need a DateTime again
DateTime dateTime = new DateTime(ticks);
Note that this will use the local date - if you're trying to retain a global timestamp, you should use DateTime.UtcNow instead of DateTime.Today.
If you really need int instead of long, you probably ought to translate and scale, e.g. to seconds since the Unix epoch.

You could either store the milliseconds from a certain point in time (that you define), or you could use a format such as yyyyMMddhhmmss (and fff if you want more precision).

The original question asks where is the error? within:
Int64 n = Int64.Parse(DateTime.Today.ToString("dd-MM-yyyy"));
The ToString(...) method generates a string representation of the date time value. In this case its argument, the string "dd-MM-yyyy" gives the format of the string to be generated. So today that will generate the string "11-01-2014". The Int64.Parse(...) attempts to parse its argument string as an integer, but here it has a mix of digits and hyphens. Hence it throws an exception.
Understanding these sort of problems can be tricky. One technique is to break the statement into smaller pieces and understand each of them in turn. When the problem is resolved the corrected pieces can be assembled into a single statement if desired. In this case the statement could be split to be:
string s = DateTime.Today.ToString("dd-MM-yyyy");
Console.WriteLine("The date string is '{0}'", s);
Int64 n = Int64.Parse(s);
Then use either a debugger or the WriteLine shown to show the value in s. Note that the WriteLine encloses the displayed value of s in quotes so that the presence or absence of spaces, newlines and other unexpected characters can easily be detected.

// the local utc offset is +2:00
public class Program
{
public static void Main(string[] args)
{
// code executed in timezone GMT+2:00
long ticksUtc = DateTime.UtcNow.Ticks;
Console.WriteLine("{0:d}",ticksUtc);
DateTime _todayUtc = new DateTime(ticksUtc);
Console.WriteLine("{0}",_todayUtc);
// get local date time from Utc time
Console.WriteLine("{0}",_todayUtc.ToLocalTime());
Console.WriteLine();
long ticksLocal = DateTime.Now.Ticks;
Console.WriteLine("{0:d}",ticksLocal);
Console.WriteLine("{0:d}",ticksLocal-ticksUtc);
DateTime _todayLocal = new DateTime(ticksLocal);
Console.WriteLine("{0}",_todayLocal);
// get the utc time from _todaylocal time
Console.WriteLine("{0}",_todayLocal.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 format a string containing numbers and characters

I have the following string "2017-2" and I need to format it as "2017-02".
var period = "2017-2";
var periodFormatted = String.Format("{0:0000-00}", period);
periodFormatted returns "2017-2"
What is the correct syntax to get the period formatted as "2017-02"?
string.Format won't know (or care) that your string contains numbers so you cannot directly format like that. You could split up the string and parse the last part as a number though. For example:
var period = "2017-2";
var parts = period.Split('-');;
var periodFormatted = $"{parts[0]}-{int.Parse(parts[1]):D2}";
However, you should probably have the period value as a proper DateTime object (or a custom type representing the year and month values) in the first place, that would have made the formatting trivial.
You can parse the input-string as DateTime and format it in a second step.
string period = "2017-2";
DateTime temp = DateTime.ParseExact(period, "yyyy-M", CultureInfo.InvariantCulture );
string result = temp.ToString("yyyy-MM");
Note: M defines the month without leading 0 and MM is always 2 digit month.
Reference: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

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!");
}

Convert Timeformat to normal datetime

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()

Parsing times above 24 hours in C#

Suppose a time stamp (just time or date and time) where the time can roll over to the next day:
00:00:00 <- midnight
01:00:00 <- 1 AM
23:00:00 <- 11 PM
24:00:00 <- midnight, day + 1
25:00:00 <- 1 AM, day + 1
What would be a way to parse it easily into a C# DateTime that would perform the carry-over to the next day? In other words, "01:00:00" would become "0001-01-01 01:00:00" and "25:00:00" would become "0001-01-02 01:00:00".
EDIT:
I should mention that this fails miserably (i.e FormatException):
DateTime.ParseExact("0001-01-01 25:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
Since you're trying to represent a period of time from an arbitrary point, rather than as a specific date, perhaps you would be better off using the System.TimeSpan class? This allows you to set values of more than 24 hours in the constructor, and can be used with DateTime objects like this:
System.TimeSpan timestamp = new System.TimeSpan(25, 0, 0);
System.DateTime parsedDateTime = new DateTime(0, 0, 0);
parsedDateTime = parsedDateTime.Add(timestamp);
Console.WriteLine(parsedDateTime.ToString("yyyy-MM-dd HH:mm:ss")); //Output as "0001-01-02 01:00:00"
NOTE: Code is untested.
EDIT: In terms of parsing the strings, I can't think of any basic .NET objects that parse strings with values greater than 23 for the hour (since 25 is an invalid hour of the day), but assuming that the format is consistent, you could create a very simple string parsing routine (or even a regular expression) to read the values individually, and load the constructor manually.
If you have an existing DateTime value you can add to, you can always use a TimeSpan:
string dt = "25:00:00";
int hours = int.Parse(dt.Split(':')[0]);
TimeSpan ts = TimeSpan.FromHours(hours);
TimeSpan.Parse() doesn't work directly in this case because it complains (fair enough!) about the 25 in the hour notation.
If you want to code it out... this should be a starting point:
string dateString = "0001-01-01 25:00:00";
string[] parts = dateString.Split(' '); //now have '0001-01-01' and '25:00:00'
string datePart = parts[0]; // '0001-01-01'
string[] timeParts = parts[1].Split(':'); //now have '25', '00', and '00
DateTime initialDate = DateTime.ParseExact(datePart, "yyyy-MM-dd", CultureInfo.InvariantCulture);//use the date as a starting point
//use the add methods to get your desired datetime
int hours = int.Parse(timeParts[0]);
int minutes = int.Parse(timeParts[1]);
int seconds = int.Parse(timeParts[2]);
DateTime resultDate = initialDate.AddHours(hours)
.AddMinutes(minutes)
.AddSeconds(seconds);
Of course, it makes assumptions that the input is formatted properly and is parsable, etc..
In addition, you could definitely use timespan instead of the individual add methods for hour, minute, second as some other answers are..
In case nobody points out an out-of-the-box answer, here is a neat ActionScript class I wrote to parse time inputs (human input)...
https://github.com/appcove/AppStruct/blob/master/Flex/AppStruct/src/AppStruct/TimeInput.as
It would be very simple to port this to C#, and you could tweak the 24 hour logic to result in #days, #hours, #minutes.
Good luck!
You are specifying an invalid date. So not only can you not parse it, you cannot store it!
How about a nice TimeSpan object instead? (It also has a Parse() method.)
Alternatively, use a sscanf()-type function like the one at http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net to extract each number separate. (Best if you have no control over the string format being read.)

Categories