I am getting date from javascript to c# in this format "/Date(1330540200000)/"
I want to convert this "/Date(1330540200000)/" format to MM:dd:yyyy format in c#.
I am able to convert it in javascript but here I want to convert this in c#.
There is a lot of javascript components that sends a a timestamp information as date. You can use a function like this:
public static DateTime ConvertTimeStampToDateTime(double value)
{
DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); //Unix Epoch on January 1st, 1970
return origin.AddMilliseconds(value);
}
After you've got the DateTime structure, you could use ToString(string format) to format as you want into a string, for sample:
// a string timeStamp (for sample, in string).
string timeStampString = "1330540200000";
// pass as a double, convert it if it is a string.
DateTime myDate = ConvertTimeStampToDateTime(double.Parse(timeStampString));
string myDateFormated = myDate.ToString("MM:dd:yyyy");
you can try this:
public static string ParseFromString(string dateTime){
return new DateTime(1970,1,1).AddMilliseconds(double.Parse(Regex.Match ("/Date(1330540200000)/", #"(\d+)").Value)).ToString("MM:dd:yyyy");
}
Related
I has in string format, timestamp 1593339378252, i need convert this, to a normal human date-20.06.2020
I try this code
var timestamp = Convert.ToInt64(dateFrom);
// Format our new DateTime object to start at the UNIX Epoch
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
// Add the timestamp (number of seconds since the Epoch) to be converted
dateTime = dateTime.AddSeconds(timestamp);
but if i try convert to int32,16,64 i get System.ArgumentOutOfRangeException
It seems that your timestamp actually contains number of milliseconds, not seconds:
new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc).AddMilliseconds(1593339378252)
// on my machine - 28-Jun-20 10:16:18 AM
You can use var dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(yourValue);
For more information, also look at the documentation
I've got a string in the following format: 05/06/2019|1330|60
The output I'm looking for is: 05/06/2019T14:30:00
I'm attempting to parse out the TimeSpan portion right now:
public static string getProcedureEndingDateTime (string input) {
//05/06/2019|1330|60
string myDate = input.Split ( '|' ) [0];
DateTime myDateTime = DateTime.Parse (myDate);
string myTime = input.Split('|')[1];
string hours = myTime.Substring(0,2);
string minutes = myTime.Substring(2,2);
TimeSpan myTimeSpan = TimeSpan.Parse($"{hours}:{minutes}");
myDateTime.Add(myTimeSpan);
return myDateTime.ToString();
}
But right now, getting the following output:
To get the above output I'm calling my function like so:
Console.WriteLine (getProcedureEndingDateTime("05/06/2019|1330|60"));
How do I parse the string "1330" into a TimeSpan?
No need to us a Timespan here, just call ParseExact instead with a proper format to do it in one line.
var myDateTime = DateTime.ParseExact("05/06/2019|1330|60", "dd/MM/yyyy|HHmm|60", CultureInfo.InvariantCulture);
Console.WriteLine(myDateTime.ToString());
//this gives 2019-06-05 1:30:00 PM, format depends on your PC's locale
I don't know what the 60 part is, you can adjust the format or substring it out beforehand.
The problem is because Add() returns a new DateTime instance, which means you're currently discarding it. Store it, and return that from your function instead, like so:
var adjusted = myDateTime.Add(myTimeSpan);
return adjusted.ToString();
Try using the numeric values as exactly that, numbers.
Also, the other issue with your code is the DateTime.Add() method doesn't add to that DateTime variable. Instead it returns a new variable, which you are ignoring.
Try this:
public static string getProcedureEndingDateTime (string input) {
string[] parts = input.Split('|');
string myDate = parts[0];
DateTime myDateTime = DateTime.Parse (myDate);
string myTime = parts[1];
if (!int.TryParse(myTime.Substring(0,2), out int hours))
hours = 0;
if (!int.TryParse(myTime.Substring(2,2), out int minutes))
minutes = 0;
TimeSpan myTimeSpan = new TimeSpan(hours, minutes, 0);
myDateTime += myTimeSpan;
return myDateTime.ToString();
}
Assuming the date shown is May 6th (and not June 5th), and also assuming the 60 represents a time zone offset expressed in minutes west of GMT, and also assuming you want the corresponding UTC value, then:
public static string getProcedureEndingDateTime (string input) {
// example input: "05/06/2019|1330|60"
// separate the offset from the rest of the string
string dateTimeString = input.Substring(0, 15);
string offsetString = input.Substring(16);
// parse the DateTime as given, and parse the offset separately, inverting the sign
DateTime dt = DateTime.ParseExact(dateTimeString, "MM/dd/yyyy|HHmm", CultureInfo.InvariantCulture);
TimeSpan offset = TimeSpan.FromMinutes(-int.Parse(offsetString));
// create a DateTimeOffset from these two components
DateTimeOffset dto = new DateTimeOffset(dt, offset);
// Convert to UTC and return a string in the desired format
DateTime utcDateTime = dto.UtcDateTime;
return utcDateTime.ToString("MM/dd/yyyy'T'HH:mm:ss", CultureInfo.InvariantCulture);
}
A few additional points:
Not only is the input format strange, but so is your desired output format. It is strange to see a T separating the date and time and also see the date in the 05/06/2019 format. T almost always means to use ISO 8601, which requires year-month-day ordering and hyphen separators. I'd suggest either dropping the T if you want a locale-specific format, or keep the T and use the standard format. Don't do both.
In ISO 8601, it's also a good idea to append a Z to UTC-based values. For DateTime values, the K specifier should be used for that. In other words, you probably want the last line above to be:
return utcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ssK", CultureInfo.InvariantCulture);
// outputs: "2019-05-06T14:30:00Z"
You might want to not format a string here, but instead return the DateTime or DateTimeOffset value. It's usually better to create a string only at the time of display.
Don't forget that the DateTime struct is immutable. In your question you were ignoring the return value of the Add method.
I am getting a date from API response as:
string jsonResponse = #"{'endDate': '/Date(-62135578800000-0500)/'}";
Now when I deserialize the reponse using NewtonSoft.json I get the result as:
MyClass obj = JsonConvert.DeserializeObject<MyClass>(jsonResponse);
Console.WriteLine(obj.endDate); // 1/1/0001 5:00:00 AM
Now again after some operation I have to post the data to the server in that same format of the date I have received:
DateTime endDateValue = new DateTime();
endDateValue = obj.endDate
MyClass objNew = new MyClass{
endDate = endDateValue
};
string jsonPostData = JsonConvert.SerializeObject(objNew);
string response = JsonConvert.SerializeObject(jsonPostData);
Console.WriteLine(response);//{"endDate":"0001-01-01T05:00:00+00:00"}
Since I don't want this format "0001-01-01T05:00:00+00:00". It should be same as '/Date(-62135578800000-0500)/'.
Till now I followed this link to understand the type of format:
PHP date format /Date(1365004652303-0500)/
I am able to get the timestamp like this:
DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
long unixTimeStampInTicks = (endDateValue.ToUniversalTime() - unixStart).Ticks;
Console.WriteLine(unixTimeStampInTicks/10000);//-62135578800000
Is there any method in c# to get the offset value -0500 present in this date object like in javascript getTimezoneOffset() method returns the offset.
Simply use DateTimeOffset, not DateTime - it's a similar structure, only with an explicit Offset property. Plain DateTime doesn't have a concept of time zones.
This means using it within MyClass, and deserializing to it.
Attached is a method I am currently using that takes in a list of DateTime strings, their input format (i.e. yyyy-MM-dd HH:mm:ss), and their offset in the form of hours.
As for the culture and "standard", I am using InvariantCulture and I am converting the times to UTC.
public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider);
int unixTime = (Int32)(result.ToUniversalTime().AddHours(hours).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc))).TotalSeconds;
return unixTime;
}
Two issues with said method:
I am using this website as a comparison. If my input is 2014-03-18 21:00:00, my output, according to my method, is 1395190800, which converts back to 2014-03-19 01:00:00. It has a four hour difference. The desired output is this:
If my input is 2014-03-18 24:00:00, I get this error:
The DateTime represented by the string is not supported in calendar System.Globalization.GregorianCalendar.
Noticeably, it does not allow the input of 24 in the HH part. This is a weird error as NodaTime handles it just fine... Though that's irrelevant as I am using DateTime.
Does anyone have any insight on this area?
EDIT:
Upon some experimentation, removing the .ToUniversalTime() removes my 4-hour offset.. Why is this happening?
public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
{
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider);
int unixTime = (Int32)(result.AddHours(hours).Subtract(new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc))).TotalSeconds;
return unixTime;
}
This document, http://www.w3.org/TR/NOTE-datetime, cited in this question How to know whether a given string is a valid UTC DateTime format? does not list 24 as a valid hour value.
This document, http://en.wikipedia.org/wiki/Iso8601, cited by an answer to the question does list 24:00 as a valid time. This one, http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight, also says 24:00 is valid.
The System.DateTime object represents hours as an integer value between 0 and 23 (see http://msdn.microsoft.com/en-us/library/vstudio/system.datetime.hour(v=vs.100).aspx). As far as I know, NodaTime doesn't use any of the .NET provided DateTime or DateTimeOffset classes and handles everything itself, which is why it's handling an hour of 24 correctly.
As for why ToUniversalTime() is adding an offset, its probably because the ParseExact is returning a date that's already been adjusted. (What is the value of result just before you call ToUniversalTime()?)
You may also want to change your call to use this overload of ParseExact instead:
result = DateTime.ParseExact(dateTimeInput, inputFormat, provider, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
This tells the parser to assume the time is in UTC if no time zone is specified in the parsed string.
As a side note, you should probably declare your Unix epoch as a readonly global variable somewhere and use TryParseExact instead of ParseExact.
public class UnixTime
{
public static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
public int unixFormat3(string dateTimeInput, string inputFormat, int hours)
{
int unixTime = -1;
DateTime result = DateTime.MinValue;
if (DateTime.TryParseExact(dateTimeInput, inputFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out result))
{
unixTime = (int)(result.AddHours(hours).Subtract(UnixTime.Epoch)).TotalSeconds;
}
return unixTime;
}
}
I have 2 DateTime objects, which I save to a file after using the ToShortDateString() function; the strings look like "12/15/2009". I am stuck on this part now, I want to initialize DateTime object(s) with these strings so I can compare the timespan between the date dates. Any help appreciated.
You can try
DateTime date = DateTime.ParseExact("12/15/2009", "MM/dd/yyyy", null);
Have a look at
DateTime.ParseExact Method (String,
String, IFormatProvider)
Easy String to DateTime, DateTime to
String and Formatting
Assuming you're reading back the dates from the file in string format
string date1 = "28/12/2009"; //this will be from your file
string date2 = "29/12/2009"; //this will be from your file
DateTime d1 = DateTime.ParseExact(date1,"dd/MM/yyyy", null);
DateTime d2 = DateTime.ParseExact(date2, "dd/MM/yyyy", null);
TimeSpan t1 = d2.Subtract(d1);
Did you try DateTime.Parse(str)?
I usually try to stick to this when dealing with DateTime/string transitions:
When persisting dates in a text format, format it explicitly. Preferably to a standardized format (such as ISO 8601).
When reading the date back, parse it to a DateTime object using the same, explicitly defined format.
This way your code will not fail when used in places where the date format differs from yours, or if the file is created on one locale, and then parsed in another.
private static string DateToString(DateTime input)
{
return input.ToString("yyyy-MM-dd");
}
private static DateTime StringToDate(string input)
{
return DateTime.ParseExact(input, "yyyy-MM-dd", CultureInfo.InvariantCulture);
}
Extract year, month and day, and than use smth like:
var dt = new DateTime(Year,Month,Day)
or crete an extension method to convert back to dateTime this kind of strings, but in general the body of that extension methad would be smth like this.