Parsing Date-and-Times from JavaScript to C# - c#

I have some JavaScript code that I'm trying to pass to my web service. My JavaScript code is supposed to send a date in UTC format. Locally, the time that I generated my code at was at 12:30:43 pm. When I executed my JavaScript code, the following date/time was generated:
2012-06-03T20:30:43.000Z
That date/time was generated from this code:
var now = new Date();
var utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
When I pass the date/time from JavaScript back to my web service, it is serialized as shown here:
20120603163043
That looks correct to me at this point. I then need to take that string and convert it to a date/time in C#. In an attempt to do that, I'm using the following C# code:
DateTime _value = DateTime.MinValue;
DateTime.TryParseExact(value, "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out _value)
When that happens, I get the following date/time.
6/3/2012 12:30:43 PM
What am I doing wrong? I was expecting the date/time to be 6/3/2012 4:30:43 PM

The result you get is correct, but please check the Kind property of your DateTime. You'll notice it's not set to UTC but to Local.
You can use DateTimeStyles.AdjustToUniversal to generate a DateTime with Kind set to UTC.
DateTime dateTime;
DateTime.TryParseExact(
value,
"yyyyMMddHHmmss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
out dateTime);
See it working on ideone.

If you just want to serialize using (e.g. webAPI) I find JS toISOString very useful and compatible.
//JAVASCRIPT
var d = new Date();
$toPut.dateTime = d.toISOString();
$toPut.put()
//C#
[Put("/setup/dateTime"), HttpPut]
public HttpResponseMessage SetDateTime([FromBody]DateTime dateTimeSettings )
That way you can keep your data structure and not deal with parsing.

You must pass date parameter to web service as UTC format and then use TryParse method to convert it to C# date object.
Try this:
//Javascript
var now = new Date(); //just like: 'Thu, 21 Mar 2013 12:44:40 GMT'
var utcNowString = now.toUTCString(); //pass this parameter to your web service
And this is C# code:
DateTime date;
DateTime.TryParse(jsDateString, out date); //parsed as: '21.03.2013 14:44:40'
Hope this helps.

Related

How to parse datetime returns from ToString

When I use the following datetime format in the Windows calendar settings.
Short date: M/d
Long time: H:mm:ss
The following code can't work.
var s = DateTime.Now.ToString(); // 4/28 8:00:00
var b = DateTime.TryParse(s, out dt); // false
The string is returned from a library, so I cannot change it, is it possible to write a parsing method that works for any kind of datetime format in the Windows calendar settings?
Update, from #MathiasR.Jessen's suggestion, I have found a solution, but it is not elegant because I have to concatenate the format string manually.
var dtf = CultureInfo.CurrentCulture.DateTimeFormat;
var fmt = dtf.ShortDatePattern + " " + dtf.LongTimePattern;
var b = DateTime.TryParseExact(s, fmt, null, DateTimeStyles.None, out dt);
Now the question changes to is there a better way?
Note that DateTime.TryParse() or DateTime.Parse() will not understand just any custom format. For custom datetime formats you need to use DateTime.TryParseExact() and DateTime.ParseExact():
Here is a demo Demo with that would be able to parse your input string.
You can Use "DatetTime.Now.ToString("yyyy-MM-dd")" it returns the value in year-shortMonth-date.
You can change the format according to your code.

Converting datetime format without using SAP RFC with C#

I got a problem when trying to convert a date-time format with SAP RFC.
I'm trying this:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
IRfcFunction SAPRateAPI = null;
SAPRateAPI = _ecc.Repository.CreateFunction("ZRFC_CUST_CONDITION_RATE");
SAPRateAPI = CreateSAPRateAPI(SAPRateAPI, argPartnerSAPTranCode, argCustSAPTranCode, argMaterialCode, date);
SAPRateAPI.Invoke(_ecc);
But getting an error 'Specified Cast is not valid'
DateTime in C# has its own representation and doesn't has any "format" which you can see or change.
So phrase "datetime in dd.mm.yyyy format" has no sense at all.
Let's look at your code:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
Here you're converting DateTime to string and then back to DateTime.
You're getting exception on back cast just because Convert uses your windows specified culture, and in the case it differs from the one in the string - you need DateTime.ParseExact and explicit format specification.
But even if this cast will be successful - you again will get DateTime and this two lines will not change its format.
It looks like all you need - is just pass date only part of datetime as argument of your function. But it can be achieved pretty easily without any casts just by using argDate.Date (assuming agrDate is DateTime)
DateTime date = new DateTime( argDate.Years, argDate.Month, argDate.Day );
I think this is what you want.
See: C# Reference
Edit:
Which is the same as Andy Korneyev solution - Ok, his is nicer too look at, but both create a second DateTime object.
Consider using the DateTime.ParseExact method.
// Parse date and time with custom specifier.
string format = "dd.mm.yyyy hh:mm:tt";
DateTime date;
try {
date = DateTime.ParseExact(argDate, format, CultureInfo.InvariantCulture);
}
catch (FormatException e) {
throw new ArgumentException("argDate", e);
}

How to format a datetime to GMT irrespective of regional settings?

I have a datetime stored in the database as GMT. I need to format this datetime as a string together with the timezone offset to UTC, for example:
DateTime date = DateTime.Parse("2012-03-15 12:49:23");
string dateAsString = date.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz");
2012-03-15T12:49:23.000+00:00
This code works on my machine in the UK. When I change my regional settings to a different time zone, for example Perth, I get the following output:
2012-03-15T12:49:23.000+08:00
I need the string output to always represent the time in GMT.
It's awkward. First you need to parse it appropriately, then format it appropriately... it's easiest to go via DateTimeOffset. (I'm assuming you intend the input string to be treated as if it's in UTC? You haven't made this clear.)
You can use DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal so that you end up with a UTC value after the Parse step. You can then create a DateTimeOffset from that DateTime value, so it will have an offset of 0.
Assuming you have a fixed format input, I would strongly advise that you use DateTime.ParseExact instead of DateTime.Parse, too. (Actually, I'd probably advise you to use Noda Time instead, but that's a different matter...)
Sample code:
using System;
using System.Globalization;
class Test
{
static void Main()
{
var parsed = DateTime.ParseExact("2012-03-15 12:49:23",
"yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
var dtOffset = new DateTimeOffset(parsed);
var output = dtOffset.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz",
CultureInfo.InvariantCulture);
Console.WriteLine(output);
}
}

Error while converting string to DateTime after publishing to web server

I am using below code
DateTime dtt=new DateTime();
dtt = Convert.ToDateTime(FromDate);
// DateTime dtt = DateTime.Parse(FromDate); //this also gives the same error
con = new MySqlConnection(conString);
con.Open();
for (int i = 1; i <= TotalDays; i++)
{
string updateHotelBooking = "Update tbl_hotelbookingdetail set `BookedRoom`=`BookedRoom`+"+1+", `AvailableRoom`=`TotalRoom`-`BookedRoom` where `HotelID`="+HotelID+" AND `CurrentDate`='"+dtt.ToString("dd-MM-yyyy")+"'";
MySqlCommand cmd7=new MySqlCommand(updateHotelBooking,con);
cmd7.ExecuteNonQuery();
dtt = dtt.AddDays(1);
}
This code is in one of my webservice which I am using for iPhone application.
here FromDate is string with value in this formate 15-11-2011 which is coming from the application in string format. I am converting it to DateTime because in loop of total days
I need to add day to dtt.
It is working fine on local host with dtt value 15-11-2011 00:00:00
but when I published it,it gives error
String was not recognize as valid DateTime
This is almost certainly because your server uses a different culture by default - and your code is just using the current thread culture.
You can specify this using DateTime.Parse - or specify the pattern explicitly with DateTime.ParseExact or DateTime.TryParseExact - but we need to know more about where the string is coming from to suggest the best approach. Is it from the user? If so, you should use the user's culture to parse it. Is it a specific format (e.g. from an XML document) instead? If so, parse using that specific format.
Ideally, get rid of the string part entirely - if you're fetching it from a database for example, can you store it and fetch it as a DateTime instead of as a string? It's worth trying to reduce the number of string conversions involved as far as possible.
EDIT: To parse from a fixed format of dd-MM-yyyy I would use:
DateTime value;
if (DateTime.TryParseExact(text, "dd-MM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out value))
{
// Value will now be midnight UTC on the given date
}
else
{
// Parsing failed - invalid data
}
What are you culture settings on your local machine and on the server?
The DateTime conversion is dependent on the current culture - dates are written quite differently in different countries.
One way to make the conversion "predictible" is to use the invariant culture:
DateTime dtt = Convert.ToDateTime(FromDate, CultureInfo.InvariantCulture);
the server date format may be in mm/dd/yyyy and you are trying to pass dd/mm/yyyy
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] dateValues = { "30-12-2011", "12-30-2011",
"30-12-11", "12-30-11" };
string pattern = "MM-dd-yy";
DateTime parsedDate;
foreach (var dateValue in dateValues) {
if (DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate))
Console.WriteLine("Converted '{0}' to {1:d}.",
dateValue, parsedDate);
else
Console.WriteLine("Unable to convert '{0}' to a date and time.",
dateValue);
}
}
}
// The example displays the following output:
// Unable to convert '30-12-2011' to a date and time.
// Unable to convert '12-30-2011' to a date and time.
// Unable to convert '30-12-11' to a date and time.
// Converted '12-30-11' to 12/30/2011.
Check this for more details
Log (or otherwise provide feedback to yourself) what FromDate is. Maybe it's empty?
May the Language Settings on the Server are different so it does not recognize the dd-MM-yyyy - try using DateTime.ParseExact(dateString, "dd-MM-yyyy", CultureInfo.InvariantCulture);

Javascript date to C# via Ajax

I have javascript date object which gives me a date string in this format, "Wed Dec 16 00:00:00 UTC-0400 2009".
I pass this via Ajax to the server (ASP.NET c#)
How can I convert, "Wed Dec 16 00:00:00 UTC-0400 2009" to a C# DateTime object. DateTime.Parse fails.
You can use DateTime.ParseExact which allows you to specify a format string to be used for parsing:
DateTime dt = DateTime.ParseExact("Wed Dec 16 00:00:00 UTC-0400 2009",
"ddd MMM d HH:mm:ss UTCzzzzz yyyy",
CultureInfo.InvariantCulture);
The most reliable way would be to use milliseconds since the epoch. You can easily get this in JavaScript by calling Date.getTime(). Then, in C# you can convert it to a DateTime like this:
long msSinceEpoch = 1260402952906; // Value from Date.getTime() in JavaScript
return new DateTime(1970, 1, 1).AddTicks(msSinceEpoch * 10000);
You have to multiply by 10,000 to convert from milliseconds to "ticks", which are 100 nanoseconds.
This may not be possible in your case, but I really recommend updating the JS code to pass dates/times in ISO 8601 format. http://en.wikipedia.org/wiki/ISO_8601
ISO 8601 is not only the formal standard, it's also easy to use and prevents a lot of timezone hassle!
To get 8601 datetime strings in Javascript:
var d = new Date();
var iso_time = d.toISOString(); //"2014-05-06T18:49:16.029Z"
To read 8601 datetime strings in C#:
DateTime d = DateTime.Parse(json_string);
Just for posterity, to help future fellow Googlers, I'd like to expand on EMP's answer.
EMP's answer provides the time in UTC (if that's what you're looking for, use that).
To arrive at the client local time in C#:
In JavaScript:
var now = new Date();
var UTC = now.getTime();
var localOffset = (-1) * now.getTimezoneOffset() * 60000;
var currentTime = Math.round(new Date(UTC + localOffset).getTime());
In C#:
DateTime currentTimeDotNet = new DateTime(1970, 1, 1).AddTicks(Convert.ToInt64(currentTime) * 10000);
Credit to this blog and EMP's answer, but took some trial and error on both ends to get it right, so just fyi for future folks.
To be honest I wouldn't try to parse that date string in C#, I'd personally try to create a more useful date structure from your javascript date object.
For instance you could use parse() in javascript which will return the ms representing the date object, which you can use DateTime.Parse() on to convert into a C# DateTime object.

Categories

Resources