how to change time format to 24hrs? in c# - c#

Literal four = new Literal();
string timeanddate;
timeanddate = DateTime.UtcNow.ToString();
DateTime dt = new DateTime();
DateTime dt_calc = new DateTime();
dt = Convert.ToDateTime(timeanddate);
dt_calc = dt.AddHours(3);
four.Text = "3hr added and this gives>> " + dt_calc.ToString();
form1.Controls.Add(four);
its all in AM PM i want to work with 24hrs

See this page for every way you could possibly want to format a DateTime.
Note that you use "HH" for 24-hour time.
For example, if you wanted the format "23:00:00" instead of "11:00:00 PM" you would use:
string formatted = dt_calc.ToString("HH:mm:ss");
By the way, your initialization of your DateTime values with new DateTime() is unnecessary.

You have to change the current culture.
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(1053);
string swedishTime = DateTime.Now.ToShortTimeString(); //24h format
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo(1033);
string englishTime = DateTime.Now.ToShortTimeString(); //am/pm format

System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern = "HH:mm:ss"

Old post, but here is the syntax from above with string interpolation:
string formatted = $"{dt_calc:HH:mm:ss}";

Related

C# ASP.NET: can't convert datetime to string

I want to convert a datetime to string.
But result now is returned as 04 August, 0016 which is not what I need.
I want result to be 04 August, 2016.
C# code:
DataTable dtGroupCurr = new DataTable();
dtGroupCurr = sourceGroupCurr.Tables[0];
var groupedCurr = (from dt2 in dtGroupCurr.AsEnumerable()
select new
{
S_DATE = dt2.Field<DateTime>("S_DATE"),
BANK_CODE = dt2.Field<string>("BANK_CODE"),
BANK_NAME = dt2.Field<string>("BANK_NAME")
}).Distinct().OrderBy(x => x.S_DATE);
foreach (var s in groupedCurr)
{
string rDate = s.S_DATE.ToString("yyyy/MM/dd");
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.Parse(rDate, culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
}
Thanks in advance ;)
Try:
string sDate = s.S_DATE.ToString("dd MMMM, yyyy", new CultureInfo("en-US", true));
Or
string rDate = s.S_DATE.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture); // To avoid override
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.Parse(rDate, culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
The "/" custom format specifier represents the date separator, which
is used to differentiate years, months, and days. The appropriate
localized date separator is retrieved from the
DateTimeFormatInfo.DateSeparator property of the current or specified
culture.
MSDN
Use the DateTime.ParseExact method and specify the format like below:
string rDate = s.S_DATE.ToString("yyyy/MM/dd");
IFormatProvider culture = new CultureInfo("en-US", true);
DateTime date = DateTime.ParseExact(rDate, "yyyy/MM/dd", culture);
string sDate = date.ToString("dd MMMM, yyyy", CultureInfo.InvariantCulture);
Use Date or DateTime.ToShortDateString();
Or
Date.ToString("dd-MM-yyyy");

Separate Date and time with " (String.Format)

Is it possible to separate Date and time with ".
So it would be:
"ddMMyyyy","HHmmss"
Right now i have:
DateTime dt = aPacket.dtTimestamp;
string d = dt.ToString("\"ddMMyyyy\",\"HHmmss\"");
and String.Format shows me just "ddMMyyyy,HHmmss"
Thank you everyone for helping me !!! But i will mark the first answer as the right one
You can try formatting:
DateTime dt = DateTime.Now;
// "01072016","101511"
string d = String.Format("\"{0:ddMMyyyy}\",\"{0:HHmmss}\"", dt);
" is a formatting character, so it needs to be escaped with \, e.g.
string d = dt.ToString("\\\"ddMMyyyy\\\",\\\"HHmmss\\\"");
You may find a verbatim string slightly more readable:
string d = dt.ToString(#"\""ddMMyyyy\"",\""HHmmss\""");
Custom Date and Time Format Strings (MSDN)
I would say like this:
var now = DateTime.Now;
var date = now.ToString("ddMMyyyy", CultureInfo.InvariantCulture);
var time = now.ToString("HHmmss", CultureInfo.InvariantCulture);
var dt = string.Format(CultureInfo.InvariantCulture, "\"{0}\",\"{1}\"", date, time);
Console.WriteLine(dt);
You can try this:
var now = DateTime.Now;
var formattedDateTime = $"{now.ToString("ddMMyyyy")},{now.ToString("HHmmss")}";

String which is not in datetime format to DateTime

I have a string which is not in a datetime format eg:20160503. How can i change it to Datetime. I tried using Substring. It is working.Is there any more efficient way? Below is what I have right now.
string a = "20160503";
int b = Convert.ToInt32(a.Substring(0, 4));
int c = Convert.ToInt32(a.Substring(4, 2));
int d = Convert.ToInt32(a.Substring(6, 2));
string date = b + "/" + c + "/" + d;
DateTime result = new DateTime();
DateTime.TryParse(date, out result);
Since you know the exact format of your datetime, you could try to use the ParseExact DateTime's method.
var dt = DateTime.ParseExact(a,"yyyyMMdd",CultureInfo.InvariantCulture);
For further info, please have a look here.
Try somthing like this:
Define your own parse format string to use.
string formatString = "yyyyMMdd";
string sample = "20160503";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
Thanks for your replies. Finaly I ended up using DateTime.TryParseExact
string dateString = "20150503";
DateTime dateValue = new DateTime();
DateTime.TryParseExact(dateString, "yyyyMMdd", new CultureInfo("en-US"), DateTimeStyles.None, out dateValue);

How Do I Convert IANA zone + datetime to UTC + Offset using NodaTime

I have local time in string format: "yyyy-MM-dd HH:mm:ss" and an IANA Time Zone for that time (e.g. "Europe/London").
How do I convert that in C#, maybe using NodaTime, to a UTC+TimeZone Offset string
e.g. "yyyy-MM-dd HH:mm:ss+01:00" ?
I don't even know where to start!
This is as far as I get (I am afraid I'm new to C sharp):
I understand I need to convert it to an instant, but just can't get to grips with the library.
string dateTime = "2014-12-31 12:30:00";
string IANA = "Europe/London";
Instant instDateTime = NodaTime.Instant.FromDateTimeUtc(Convert.ToDateTime(dateTime));
string outputUTC = string.Format("yyyy-MM-dd HH:mm:ssZ", instDateTime);
Thanks to Matt (see answer below), I now have the functions I needed (Note that in the end what I needed was UTC and not date time + offset):
What is a little worrying is that is says that Europe/Moscow is UTC+04:00, whereas it is actually UTC+03:00 since 26 October 2014.
static void Main(string[] args)
{
string dateTime = "2014-12-31T12:30:00";
string timeZone = "Europe/Moscow";
Console.WriteLine(timeZone + " Local time '" + dateTime + "' to Zulu time");
Console.WriteLine(ConvertIANALocalTimeToZulu(timeZone, dateTime));
Console.WriteLine();
Console.WriteLine("Zulu time '" + dateTime + "' to " + timeZone + " local time");
Console.WriteLine(ConvertZuluTimeToIANALocalTime(timeZone, dateTime));
Console.ReadLine();
}
static string ConvertIANALocalTimeToZulu(string timeZoneIANA, string localDateTime)
{
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-ddTHH:mm:ss");
LocalDateTime ldt = pattern.Parse(localDateTime).Value;
ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZoneIANA]);
Instant instant = zdt.ToInstant();
ZonedDateTime zulu = instant.InUtc();
////string output = zulu.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
string output = zulu.ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
return output;
}
static string ConvertZuluTimeToIANALocalTime(string timeZoneIANA, string zuluDateTime)
{
var pattern = InstantPattern.CreateWithInvariantCulture("yyyy-MM-ddTHH:mm:ss");
Instant instant = pattern.Parse(zuluDateTime).Value;
ZonedDateTime zdt = instant.InZone(DateTimeZoneProviders.Tzdb[timeZoneIANA]);
////string output = zdt.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
string output = zdt.ToString("yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);
return output;
}
It's unclear from your question if you meant that the original value was in UTC or in local time.
If it's in UTC, then do the following:
string dateTime = "2014-12-31 12:30:00";
string timeZone = "Europe/London";
var pattern = InstantPattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss");
Instant instant = pattern.Parse(dateTime).Value;
ZonedDateTime zdt = instant.InZone(DateTimeZoneProviders.Tzdb[timeZone]);
string output = zdt.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
If it's in local time, then do this instead:
string dateTime = "2014-12-31 12:30:00";
string timeZone = "Europe/London";
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt = pattern.Parse(dateTime).Value;
ZonedDateTime zdt = ldt.InZoneLeniently(DateTimeZoneProviders.Tzdb[timeZone]);
string output = zdt.ToString("yyyy-MM-dd HH:mm:sso<m>", CultureInfo.InvariantCulture);
Also - you should note that in December, London is on GMT (UTC+00:00) - so the output of either function will be "2014-12-31 12:30:00+00:00" for the values you provided.

convert C# date time to string and back

I'm converting C# date time to string. Later when I convert it back to DateTime object it appears that they are not equal.
const string FMT = "yyyy-MM-dd HH:mm:ss.fff";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Here is the example. Looks like everything is included in string format, when I print date both displays the same, but when I compare objects or print date in binary format I see the difference. It looks strange to me, could you please explain what is going on here?
Here is the output for the code above.
-8588633131198276118
634739049656490000
You should use the roundtrip format specifier "O" or "o" if you want to preserve the value of the DateTime.
The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.
Using your code (apart from changing the format string):
const string FMT = "O";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
I get:
-8588633127598789320
-8588633127598789320
Oded's answer is good but it didn't work for me for UTC dates. In order to get it to work for UTC dates, I needed to specify a DateTimeStyles value of "RoundtripKind" so that it didn't try to assume it was a local time. Here is the updated code from above:
const string FMT = "O";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Note, this works for both UTC and local dates.
2 things:
You can use the ParseExact overload that takes a DateTimeStyle parameter in order to specify AssumeLocal.
There will still be a small difference between now1 and now2 unless you increase the precision to 7 digits instead of 3: "yyyy-MM-dd HH:mm:ss.fffffff"
const string FMT = "yyyy-MM-dd HH:mm:ss.fffffff";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Even without the above changes, the calculated difference between now1 and now2 appears small, even though the binary values do not appear similar.
TimeSpan difference = now2.Subtract(now1);
Console.WriteLine(difference.ToString());
If you dont need the string to be human-readable (like, you want to cipher it before storage), you can just call string str = dt1.ToBinary().ToString(); and DateTime dt2 = DateTime.FromBinary(long.Parse(str));
DateTime now1 = DateTime.Now;
string strDate = now1.ToBinary().ToString();
DateTime now2 = DateTime.FromBinary(long.Parse(strDate));
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Just use this code it convert date time to string and string to date time
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace DateTimeConvert
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = ConvDate_as_str(textBox1.Text);
}
public string ConvDate_as_str(string dateFormat)
{
try
{
char[] ch = dateFormat.ToCharArray();
string[] sps = dateFormat.Split(' ');
string[] spd = sps[0].Split('.');
dateFormat = spd[0] + ":" + spd[1] + " " + sps[1];
DateTime dt = new DateTime();
dt = Convert.ToDateTime(dateFormat);
return dt.Hour.ToString("00") + dt.Minute.ToString("00");
}
catch (Exception ex)
{
return "Enter Correct Format like <5.12 pm>";
}
}
private void button2_Click(object sender, EventArgs e)
{
label2.Text = ConvDate_as_date(textBox2.Text);
}
public string ConvDate_as_date(string stringFormat)
{
try
{
string hour = stringFormat.Substring(0, 2);
string min = stringFormat.Substring(2, 2);
DateTime dt = new DateTime();
dt = Convert.ToDateTime(hour+":"+min);
return String.Format("{0:t}", dt); ;
}
catch (Exception ex)
{
return "Please Enter Correct format like <0559>";
}
}
}
}

Categories

Resources