I converted 2014-08-21 12:00 AM to 2014-08-21T18:30:00.000Z using
ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffK")
But now i want to reverse it.
How can i convert 2014-08-21T18:30:00.000Z to 2014-08-21 12:00 AM?
Here you go:
var localFormat = "MM-dd-yyyy HH:mm tt";
string universalFormat = "yyyy-MM-dd'T'HH:mm:ss.fffK";
var now = DateTime.Now;
Console.WriteLine(now.ToString(localFormat));
var universal = now.ToUniversalTime().ToString(universalFormat);
Console.WriteLine(universal);
var newNow = Convert.ToDateTime(universal).ToLocalTime().ToString(localFormat);
Console.WriteLine(newNow);
Output:
8/24/2014 11:16 PM
2014-08-25T06:16:45.229Z
8/24/2014 11:16 PM
Last one is a string, just like the universal one, but you may forgo the ToString() conversion and simply format it on demand. Up to you, I simply provide the foundation code.
EDIT:
Per OP's request in the comments:
// Here's one way of converting a string to DateTime.
var date = Convert.ToDateTime("8/24/2014 11:16:45 PM");
// Here's one way of creating DateTime by providing arguments.
var date = new DateTime(2014, 8, 24, 23, 16, 45);
I'd also recommend providing localization as one of the arguments, just to be safe. Once you have those variables, you may do all the same actions as the prior code showcased.
If you want just the date or just the time, simply format your output accordingly:
// If you want strings.
date.ToString("MM-dd-yyyy");
date.ToSTring("HH:mm:ss");
// If you want DateTime and TimeSpan
date.Date();
date.TimeOfDay();
I just did this in LINQPad:
var dt = DateTime.Parse("2014-08-21 12:00 AM")
.ToUniversalTime()
.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
var dtReverse = DateTime.Parse("2014-08-20T18:30:00.000Z")
.ToLocalTime()
.ToString("yyyy-MM-dd h:mm tt");
My results:
2014-08-20T18:30:00.000Z
2014-08-21 12:00 AM
You may simply try this:
TimeZone.CurrentTimeZone.ToLocalTime(date);
Also check DateTimeOffSet
Represents a point in time, typically expressed as a date and time of
day, relative to Coordinated Universal Time (UTC).
Also
DateTime changedDate = DateTime.SpecifyKind(DateTime.Parse(dateStr),
DateTimeKind.Utc);
DateTime dt = convertedDate.ToLocalTime();
Related
If I have a string like 15:00 and I parse this to DateTime ot DateTimeOffset, the date is set to today.
I want somehow to distinguish, if the date part is given or not. It would help, if the date part is not given, the date is 1.1.1970.
Is there a better possibility instead of using regex and parse this by my own?
Try to parse the value as TimeSpan and then try to parse it as DateTime.
var data = "15:00";
if (TimeSpan.TryParse(data, out var time))
{
Console.WriteLine("Time: {0}", time);
}
else if (DateTime.TryParse(data, out var datetime))
{
Console.WriteLine("DateTime: {0}", datetime);
}
else
{
Console.WriteLine("I don't know how to parse {0}", data);
}
If I have a string like "15:00" and I parse this to DateTime ot
DateTimeOffset, the date is set to today.
This is by design.
From DateTime.Parse doc:
A string with a time but no date component. The method assumes the
current date unless you call the Parse(String, IFormatProvider,
DateTimeStyles) overload and include
DateTimeStyles.NoCurrentDateDefault in the styles argument, in which
case the method assumes a date of January 1, 0001.
From DateTimeOffset.Parse doc:
If is missing, its default value is the current day.
So, for DateTime, if you don't use any DateTimeStyles, you get the current date
var hours = "15:00";
var date = DateTime.Parse(hours, CultureInfo.InvariantCulture); // 12/9/2018 3:00:00 PM
but if you use DateTimeStyles.NoCurrentDateDefault as a third parameter;
var hours = "15:00";
var date = DateTime.Parse(hours, CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);
// 1/1/0001 3:00:00 PM
But I think your problem keeps on that sentence; "if the date part is given or not.." How did you decide your string has date part or not? Is it always have 5 characters as Steve commented? It can be in a format like 4:00? What about 4:1? If it can be like 4:1, it should be parsed as 4:10 or 4:01?
So, you need to decide first what is the meaning of "if the date part is given or not.." for your case. Then you can easily parse your string to TimeSpan, not DateTime in my opinion, so, you can add it created manually "1.1.1970" with DateTime(int, int, int) constructor.
if(YourConditionForYourStringNotIncludingDatePart)
{
var time = TimeSpan.Parse("15:00");
var date = new DateTime(1970, 1, 1);
var result = date.Add(time);
}
Using regular expressins for DateTime parsing is usually a bad idea. I wouldn't suggest to use it unless you have no other way to do it for DateTime.
I think for that case you could things keep simple. This could be a solution that not depends on the lenght when there is only a timepart:
void Main()
{
Console.WriteLine(ParseWithDummyIfDateAbsent("15:00", new DateTime(1970, 1, 1)));
Console.WriteLine(ParseWithDummyIfDateAbsent("15:00:22", new DateTime(1970, 1, 1)));
Console.WriteLine(ParseWithDummyIfDateAbsent("09.12.2018 15:00", new DateTime(1970, 1, 1)));
}
DateTime ParseWithDummyIfDateAbsent(string input, DateTime dummyDate)
{
if(TimeSpan.TryParse(input, out var timeSpan))
input = $"{dummyDate.Date.ToShortDateString()} {input}";
return DateTime.Parse(input);
}
Output:
01.01.1970 15:00:00
01.01.1970 15:00:22
09.12.2018 15:00:00
Depends on your localization:-)
I have datetime string
dateStr = "2017-03-21T23:00:00.000Z";
then I am calling
var date = DateTime.Parse(dateStr);
and unexpectedly my date equals
22.03.2017 00:00:00
I expected it to be 21.03.2017
What's going on here?
DateTime.Parse() is locale specific and will take into account your local time zone when parsing dates.
If you are in CET (Central European Time) during the winter your offset is one hour ahead of UTC. The date given is marked with a Z indicating it is in UTC, so DateTime.Parse() will adjust that to your local timezone.
There is an override that allows you to change that behaviour if you want, by specifying a specific DateTimeStyles enum. DateTimeStyles.AdjustToUniversal is what you are looking for as that should keep the DateTime as UTC.
And if you only want the date part afterwards, you can just call .Date on the DateTime object you got back from Parse()
So, something like this:
var date = DateTime.Parse(dateStr, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).Date;
if the date format does not change then you can use the below code to get date part from date string. But it is a bit risky due to its strict dependency on the input format.
string dateStr = "2017-03-21T23:00:00.000Z";
int year = Int32.Parse(dateStr.Substring(0, 4));
int month = Int32.Parse(dateStr.Substring(5, 2));
int day = Int32.Parse(dateStr.Substring(8, 2));
var date = new DateTime(year, month, day);
Console.WriteLine(date);
Because the format of type 'DateTime' variable is 'YYYY-MM-DD hh:mm:ss'.
If you run this code:
var dt = DateTime.Now;
Console.WriteLine(dt);
You'll see '24/03/2017 12:54:47'
If you have 'YYYY-MM-DD' format, add .ToString("dd-MM-yyyy"), then:
string dateStr = "2017-03-21T23:00:00.000Z";
var date = DateTime.Parse(dateStr).ToString("dd-MM-yyyy");
Result:'24-03-2017'
I have date and time strings already in UTC. I need to use those strings to create a DateTime object.
This is the code I'm using. The problem is the time gets converted and my UTC time on the datetime object is no longer correct. I'm giving UTC values so they shouldn't get converted again.
string format = $"{dateFormat}_{timeFormat}";
string value = $"{dateValue}_{timeValue}";
var x = DateTimeOffset.ParseExact(value, format, CultureInfo.CurrentCulture).UtcDateTime;
where dateFormat = "ddMMyy", timeFormat = "HHmmss", dateValue = "191194" and timeValue = "225446".
D Stanley's answer certainly works, but is slightly more complex than you need - if you want a DateTime as the result, you don't need to use DateTimeOffset at all, as DateTime.ParseExact handles DateTimeStyles.AssumeUniversal as well, although you need to specify AdjustToUniversal so that the result is in UTC. (Otherwise it's adjusted to the local time zone automatically - and unhelpfully, IMO, but that's a battle for another day.)
var x = DateTime.ParseExact(
value,
format,
CultureInfo.CurrentCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Sample code (that revealed to me the need for DateTimeStyles.AdjustToUniversal):
using System;
using System.Globalization;
class Test
{
static void Main(string[] args)
{
string text = "2015-06-10 20:52:13";
string format = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(
text,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Console.WriteLine(dateTime); // 10/06/2015 20:52:13 on my box
Console.WriteLine(dateTime.Kind); // Utc
}
}
I'd be careful using CultureInfo.CurrentCulture, by the way - bare in mind the fact that it can affect the calendar system in use as well as format strings etc.
(As a side-note of course, I'd recommend using my Noda Time library instead. In this case I'd probably suggest parsing your time using a LocalTimeFormat, your date using a LocalDateFormat, then adding the results together to get a LocalDateTime that you could then convert to a ZonedDateTime using UTC. Or you could use your existing approach to create a ZonedDateTimePattern or InstantPattern, of course.)
Use the overload of DateTimeOffset.ParseExact that takes a DateTimeStyles value:
var x = DateTimeOffset.ParseExact(value,
format,
CultureInfo.CurrentCulture,
DateTimeStyles.AssumeUniversal)
.UtcDateTime;
Note that the call to UtcDateTime doesn't hurt anything, but the time will already be in UTC time (which is what you want) so it will give you back the equivalent DateTime value. You can just use DateTime.ParseExact as Jon suggests, which has the same overload.
This solution also will be helpful if you have your date not as one string.
Just use DateTimeKind.Utc as constructor parameter of DateTime:
new DateTime(2020, 05, 07, 18, 33, 0, DateTimeKind.Utc);
I have a value stored in variable of type System.TimeSpan as follows.
System.TimeSpan storedTime = 03:00:00;
Can I re-store it in another variable of type String as follows?
String displayValue = "03:00 AM";
And if storedTime variable has the value of
storedTime = 16:00:00;
then it should be converted to:
String displayValue = "04:00 PM";
You can do this by adding your timespan to the date.
TimeSpan timespan = new TimeSpan(03,00,00);
DateTime time = DateTime.Today.Add(timespan);
string displayTime = time.ToString("hh:mm tt"); // It will give "03:00 AM"
Very simple by using the string format
on .ToSTring("") :
if you use "hh" ->> The hour, using a 12-hour clock from 01 to 12.
if you use "HH" ->> The hour, using a 24-hour clock from 00 to 23.
if you add "tt" ->> The Am/Pm designator.
exemple converting from 23:12 to 11:12 Pm :
DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt"); // this show 11:12 Pm
var res2 = d.ToString("HH:mm"); // this show 23:12
Console.WriteLine(res);
Console.WriteLine(res2);
Console.Read();
wait a second, there is a catch, the system Culture !!, the same code executed on windows set to different language
especially with different culture language will generate different result.
for example in windows set to Arabic language the result Will be like this :
// 23:12 م
م means Evening (first letter of مساء) .
in windows set to German language i think it will show // 23:12 du.
you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it, do a rebuild (execute) of your app and watch what i'm talking about.
so how can you force showing Am and Pm prefix in English event if the culture of the current system isn't set to English ?
easy just by adding two lines ->
the first step add using System.Globalization; on top of your code
and modify the previous code to be like this :
DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show 11:12 Pm
InvariantCulture => using default English Format.
another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?
Solution for Arabic Exemple :
DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE"));
this will show // 23:12 م
event if my system is set to English region format.
you can change "ar-AE" if you want to another language format. there is a list for each language.
exemples :
ar ar-SA Arabic
ar-BH ar-BH Arabic (Bahrain)
ar-DZ ar-DZ Arabic (Algeria)
ar-EG ar-EG Arabic (Egypt)
.....
You can add the TimeSpan to a DateTime, for example:
TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");
Demo: http://ideone.com/veJ6tT
04:00 PM
Standard Date and Time Format Strings
Doing some piggybacking off existing answers here:
public static string ToShortTimeSafe(this TimeSpan timeSpan)
{
return new DateTime().Add(timeSpan).ToShortTimeString();
}
public static string ToShortTimeSafe(this TimeSpan? timeSpan)
{
return timeSpan == null ? string.Empty : timeSpan.Value.ToShortTimeSafe();
}
string displayValue="03:00 AM";
This is a point in time , not a duration (TimeSpan).
So something is wrong with your basic design or assumptions.
If you do want to use it, you'll have to convert it to a DateTime (point in time) first. You can format a DateTime without the date part, that would be your desired string.
TimeSpan t1 = ...;
DateTime d1 = DateTime.Today + t1; // any date will do
string result = d1.ToString("hh:mm:ss tt");
storeTime variable can have value like
storeTime=16:00:00;
No, it can have a value of 4 o'clock but the representation is binary, a TimeSpan cannot record the difference between 16:00 and 4 pm.
You will need to get a DateTime object from your TimeSpan and then you can format it easily.
One possible solution is adding the timespan to any date with zero time value.
var timespan = new TimeSpan(3, 0, 0);
var output = new DateTime().Add(timespan).ToString("hh:mm tt");
The output value will be "03:00 AM" (for english locale).
You cannot add AM / PM to a TimeSpan. You'll anyway have to associate the TimaSpan value with DateTime if you want to display the time in 12-hour clock format.
TimeSpan is not intended to use with a 12-hour clock format, because we are talking about a time interval here.
As it says in the documentation;
A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date. Otherwise, the DateTime or DateTimeOffset structure should be used instead.
Also Microsoft Docs describes as follows;
A TimeSpan value can be represented as [-]d.hh:mm:ss.ff, where the optional minus sign indicates a negative time interval, the d component is days, hh is hours as measured on a 24-hour clock, mm is minutes, ss is seconds, and ff is fractions of a second.
So in this case, you can display using AM/PM as follows.
TimeSpan storedTime = new TimeSpan(03,00,00);
string displayValue = new DateTime().Add(storedTime).ToString("hh:mm tt");
Side note :
Also should note that the TimeOfDay property of DateTime is a TimeSpan, where it represents
a time interval that represents the fraction of the day that has elapsed since midnight.
To avoid timespan format limitations, convert to datetime.
Simplest expression would be:
// Where value is a TimeSpan...
(new DateTime() + value).ToString("hh:mm tt");
Parse timespan to DateTime and then use Format ("hh:mm:tt"). For example.
TimeSpan ts = new TimeSpan(16, 00, 00);
DateTime dtTemp = DateTime.ParseExact(ts.ToString(), "HH:mm:ss", CultureInfo.InvariantCulture);
string str = dtTemp.ToString("hh:mm tt");
str will be:
str = "04:00 PM"
You can try this:
string timeexample= string.Format("{0:hh:mm:ss tt}", DateTime.Now);
you can remove hh or mm or ss or tt according your need
where
hh is hour in 12 hr formate,
mm is minutes,ss is seconds,and tt is AM/PM.
Parse timespan to DateTime. For Example.
//The time will be "8.30 AM" or "10.00 PM" or any time like this format.
public TimeSpan GetTimeSpanValue(string displayValue)
{
DateTime dateTime = DateTime.Now;
if (displayValue.StartsWith("10") || displayValue.StartsWith("11") || displayValue.StartsWith("12"))
dateTime = DateTime.ParseExact(displayValue, "hh:mm tt", CultureInfo.InvariantCulture);
else
dateTime = DateTime.ParseExact(displayValue, "h:mm tt", CultureInfo.InvariantCulture);
return dateTime.TimeOfDay;
}
At first, you need to convert time span to DateTime structure:
var dt = new DateTime(2000, 12, 1, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds)
Then you need to convert the value to string with Short Time format
var result = dt.ToString("t"); // Convert to string using Short Time format
Because this situation is as annoying as it is common... I created a helper class, which I have released in a NuGet package. This could be a private method and can be used in MVC views as well as in back-end C# code.
public static string AsTimeOfDay(TimeSpan timeSpan, TimeSpanFormat timeSpanFormat = TimeSpanFormat.AmPm)
{
int hours = timeSpan.Hours;
int minutes = timeSpan.Minutes;
string AmOrPm = "AM";
string returnValue = string.Empty;
if (timeSpanFormat == TimeSpanFormat.AmPm)
{
if (hours >= 12)
{
AmOrPm = "PM";
}
if (hours > 12)
{
hours -= 12;
}
TimeSpan timeSpanAmPm = new TimeSpan(hours, minutes, 0);
returnValue = timeSpanAmPm.ToString(#"h\:mm") + " " + AmOrPm;
}
else
{
returnValue = timeSpan.ToString(#"h\:mm");
}
return returnValue;
}
If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm
How can I just extract the date from the timestamp?
For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it.
What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time?
DateTime.Parse("2010-05-18 08:36:52:236").ToString("yyyy-MM-dd");
You should use the DateTime type:
DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");
Your format is non-standard, so you'll need to call ParseExact instead of Parse:
DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);
You could use substring:
"2010-05-18 08:36:52:236".Substring(0, 10);
Or use ParseExact:
DateTime.ParseExact("2010-05-18 08:36:52:236",
"yyyy-MM-dd HH:mm:ss:fff",
CultureInfo.InvariantCulture)
.ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
date = date.Date; // Get's the date-only component.
// Do something cool.
}
else
{
// Flip out because you didn't get a real date.
}
Get the .Date member on the DateTime
DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
use it like this:
var x = DateTime.Now.Date; //will give you midnight today
x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.
The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part.
Try this:
select convert(datetime,convert(int, #yourdate))
So you convert it to an integer and then back to a data and voila, time part is gone.
Of course subtracting this result from the original value will give you the time part only.