How to get current time in T07:07:45-0500 format - c#

I want to get the current time in T07:07:45-0500 format.
I have try like this:
DateTime currentDate = DateTime.Now;
String currentTime = currentDate.ToString("'T'HH':'mm':'ssK");
Console.WriteLine("DOB ==> " + dateOfBirth.ToString("yyyy-MM-dd") + currentTime);
But the result is 1986-07-11T07:07:45-05:00
I want result like 1986-07-11T07:07:45-0500
Is there any way to get the current time in T07:07:45-0500 format.
Please help me to resolve my problem.

I don't think the .NET custom date and time format strings allow that format. You could use my Noda Time project easily enough, using DateTimeOffset.Now if you want the system default time zone to be applied. (It can be done explicitly
For example:
var odt = OffsetDateTime.FromDateTimeOffset(DateTimeOffset.Now);
var pattern = OffsetDateTimePattern.CreateWithInvariantCulture(
"yyyy-MM-dd'T'HH:mm:sso<+HH:mm>");
Console.WriteLine(pattern.Format(odt));
As noted in comments, you're currently doing something very odd in terms of combining the values. If you really want to do that, I would personally create an appropriate OffsetDateTime like this:
LocalDate dateOfBirth = ...; // Wherever that comes from
OffsetDateTime now = OffsetDateTime.FromDateTimeOffset(DateTimeOffset.Now);
OffsetDateTime mixture = dateOfBirth.At(now.LocalTime).WithOffset(now.Offset);
var pattern = ...; // as before
Console.WriteLine(pattern.Format(mixture));
That makes it clearer how you're combining the values.

I think the representation of an offset depends on how your CurrentCulture represents UTC Offset value. It might be the formats as -05:00, -0500, or simply -05.
Based on comments, looks like UTC Offset format is hard-coded and it doesn't depends on any culture.
You should clearly find the last index of : character and replace it with empty string. I don't think there is another solution for this in .NET Framework.
DateTime currentDate = DateTime.Now;
String currentTime = currentDate.ToString("'T'HH':'mm':'ssK");
currentTime = currentTime.Remove(currentTime.LastIndexOf(":"), 1);

Related

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#: Code Optimization for Date Formatting

Using C#, I am trying to populate a variable with a known filename + date. The catch is that the date must always be the last day of the previous month. It must also have no slashes or hyphens, and the year must be two digits. For example, if it is now November 27 2015, I need my filename to be: Foobar_103115.txt
As a programmer who still has much to learn, I have written the clunky code below and it does achieve my desired result, even though it will obviously break after the end of this century. My code is written this way because I could not figure out a more direct syntax for getting the date I want, complete with the specified formatting.
My question is this: What would be a more elegant and efficient way of recreating the below code?
I have commented all the code for any novice programmers who might be interested in this. I know the experts I'm asking for help from don't need it.
public void Main()
{
String Filename
DateTime date = DateTime.Today;
var FirstDayOfThisMonth = DateTime.Today.AddDays(-(DateTime.Today.Day - 1)); //Gets the FIRST DAY of each month
var LastDayOfLastMonth = FirstDayOfThisMonth.AddDays(-1); //Subtracts one day from the first day of each month to give you the last day of the previous month
String outputDate = LastDayOfLastMonth.ToShortDateString(); //Reformats a long date string to a shorter one like 01/01/2015
var NewDate = outputDate.Replace("20", ""); //Gives me a two-digit year which will work until the end of the century
var NewDate2 = NewDate.Replace("/", ""); //Replaces the slashes with nothing so the format looks this way: 103115 (instead of 10/31/15)
Filename = "Foobar_" + NewDate2 + ".txt"; //concatenates my newly formatted date to the filename and assigns to the variable
Sounds like you want something more like:
// Warning: you should think about time zones...
DateTime today = DateTime.Today;
DateTime startOfMonth = new DateTime(today.Year, today.Month, 1);
DateTime endOfPreviousMonth = startOfMonth.AddDays(-1);
string filename = string.Format(CultureInfo.InvariantCulture,
"FooBar_{0:MMddyy}.txt", endOfPreviousMonth);
I definitely wouldn't use ToShortDateString here - you want a very specific format, so express it specifically. The results of ToShortDateString will vary based on the current thread's culture.
Also note how my code only evaluates DateTime.Today once - this is a good habit to get into, as otherwise if the clock "ticks" into the next day between two evaluations of DateTime.Today, your original code could give some pretty odd results.

Count forward and check date forward

this is how I would like that to build up such that it has the date today d 2 / 23-2015 and so it goes 30 days ahead of the date, which means it will be d 22.02.2015,
I've tried to do like this:
string datoTid = DateTime.Now.ToString("dd-MM-yyyy");
DateTime equalsDato = datoTid.AddDays(1 * 30);
string slutdato = equalsDato.ToString("dd-MM-yyyy");
This should work:
string slutdato = DateTime.Now.AddDays(1 * 30).ToString("dd-MM-yyyy");
I'm not entirely sure what your asking, I believe your intent is to take the current date and added thirty days. Which would be:
var date = DateTime.Now.AddDays(30);
This would provide a type of DateTime. Then you can create a string representation of the designated DateTime. (In your desired format)
date.ToString("dd-MM-yyyy");
This would provide your modification for the format, while simply applying the designated date ahead.

How to convert a date of integers to a formated date string (i.e. 2012009 to 2/01/2009)

Any ideas?
I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Since the date is stored as a string, you may want to use ParseExact:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider is null, which uses the current culture.
Depending on style you may wish to use TryParseExact.
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..

How would I make a datetime into a specific custom format?

Say the current date is 1st Mar 2010, I want to display it like this...
20100301 so like first 4 digits = year, 2 digits = Month, 2 digits = day
is there an easy way to do this?
use format
yourdatetimeObj.ToString("yyyyMMdd");
Ref: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Something like
dateTimeObject.ToString("yyyyMMdd");
See String Format for DateTime
var mydate = DateTime.Now; // Whatever you want.
mydate.ToString("yyyyMMdd");
Look at DateTimeFormatInfo for the other custom format strings you can use.
You can either use the ToString() implementation of the DateTime class, like the examples already given, or use a format string to display it along with other information, like so:
var now = DateTime.Now;
var msg = String.Format("Now: {0:dd/MM/yyyy}", now);
Or
Console.Write("Now: {0:MM/dd/yyyy}", now);

Categories