Convert.ToDateTime in C# behave different from one environment to another - datetime

I have the following line of code in C#:
DateTime dtReportDate = Convert.ToDateTime(_ReportDate);
The _ReportDate is an string variable and it's value is: 21/05/2013 (dd/MM/yyyy). So I try to convert that date to a DateTime variable and the do the following:
_ReportDate = string.Format("{0:yyyy/MM/dd}", dtReportDate) + " " + _ReportHour;
As you can see I need to concatenate the date and hour in the format: yyyy/MM/dd HH:mm.
When running those lines of codes locally it works OK. But, when I put it in a Dev server it throws the following error: String was not recognized as a valid DateTime.
So, I would like to ask a couple of questions. Does this error could be related with any configuration of the server? Why the Convert.ToDateTime works OK locally but in the server it doesn't?
Any clue would be fine
Thanks

I have figure out how to solve this problem executing the following line of code:
//Attempts to Parse the Date using the format specified (the third parameter can also be null)
DateTime dtReportDate = DateTime.ParseExact(_ReportDate,"dd/MM/yyyy", CultureInfo.InvariantCulture);
Hope this help others

Related

Format Date via Parameter

I have a DateTime variable (default formatting), and I would like to format it to a format to I receive from a string parameter.
I normally do something similar to: {myDate:yyyy-MM-dd}, and it works properly.
Now I have a lot of possible date formats and need to format according to the chosen one.
I have tried the following but returned garbage (ae0aor0aa):
string testFormat = "yyyy. MM. dd.";
{myDate:testFormat }
I have also tried to convert the date to string and back to date with ParseExact, but gave me an invalid date exception. NB: the date in myDate is valid, as I have checked it with the debugger.
Can you kindly advise?
Thanks to apc, it was easily solved by myDate.ToString(testFormat)

FTL Date Formatting In Netsuite

I have a date coming through as 25/4/2022. I need it changed to 25/APRIL/2022. I have tried every combination of ?date('dd/mm/yyyy') / ?datetime('dd/mmm/yyyy') ?datetime(dd/mm/yyyy)?string('dd/mmm/yyyy') that I can think of but I keep getting teh same type of errors:
The string doesn't match the expected date/time/date-time format.
The nested reason given follows: Unparseable date: "" ---- FTL stack trace ("~" means nesting-related)
What am I missing here?
You need to use a Java SimpleDateFormat pattern to format dates. If you want the month, use M (uppercase), as m (lowercase) is minutes in hour. For a full month, use MMMM. So, use:
${"25/April/2022"?date("dd/MMMM/yyyy")}
See also:
https://freemarker.apache.org/docs/ref_builtins_string.html#ref_builtin_string_date
https://freemarker.apache.org/docs/ref_directive_setting.html#topic.dateTimeFormatSettings
How to parse month full form string using DateFormat in Java?

Tabulator Cell datetime object - Need to Format

I am attempting to reformat a datetime value in a cell that contains TZ UTC data. An example value is: 2019-12-09T14:50:47.000Z-0500
I need it to display as:
MM/DD/YYYY HH:mm:ssXM - ex: 12/09/2019 02:50:47PM
Local time, of course.
I have tried reading the moment.js doc without success. Here is a snippet I have attempted. The table shows up with "blank rows." If I remove the formatting, the data shows correctly but not with the date and time format I would like.
{title:"Last Submitted", field:"createdOn", sorter:"date", formatter:"datetime", formatterParams:{inputFormat:"YYYY-MM-DD hh:mm:ss", outputFormat:"MM/DD/YYYY", invalidPlaceholder:"(Invalid date)"}},
Any assistance would be greatly appreciated!
Ben
UPDATE BASED ON ANSWER 12/26/2019
Thank you again for responding. However, this is perhaps an issue for the author of Tabulator since I copied the inputFormat and outputFormat verbatim into the column definition of a Tabulator component and it displays blank rows. If I remove the column cell formatter (which is a wrapper around moment.js code), the list displays with the full timestamp (including UTC / zulu time).
ex:
2019-12-09T12:50:47.000Z-0500
Expected result (either 24h or 12h format doesn't matter at this point - and I did try to remove the "A" for the AM/PM indicator)
Unfortunately, I cannot upload the code for this project since it makes internal WS calls for JSON results (which is another issue - Remote Pagination does not appear to be working.)
Here is the source code for the column:
{title:"Last Submitted", field:"createdOn", sorter:"date", formatter:"datetime", formatterParams:{inputFormat:"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]Z", outputFormat:"MM/DD/YYYY HH:mm:ssA",invalidPlaceholder:"(Invalid date)"}},
As stated above, if I add the formatter, blank table appear and nothing else. If I remove the formatter all data is displayed including the unformatted date (well it's formatted in a way in which I nor my users will want).
Any ideas would be greatly appreciated!
Image of Result with datetime formatter
With momentjs you can parse date if you know the format of an input string:
moment(inDate, inFormat);
For example:
moment('12-25-1995', 'MM-DD-YYYY');
In your case format of an input string is YYYY-MM-DD[T]HH:mm:ss.SSS[Z]Z - square brackets work as escape characters.
You can get formatted string from moment object with .format method:
moment().format(outFormat);
For example:
moment().format('MM-DD-YYYY');
In your case format of an output string is MM/DD/YYYY HH:mm:ssA - you can read more in docs
You can see how both parsing and formatting work together in the snippet below:
let inDate = '2019-12-09T14:50:47.000Z-0500',
inFormat = 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]Z',
outFormat = 'MM/DD/YYYY HH:mm:ssA',
outDate = moment(inDate, inFormat).format(outFormat);
console.log(`In Date: ${inDate}`);
console.log(`Out Date: ${outDate}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

CAST() not changing to datetime format

I am using this SQL query to convert my _Submission_date column which of type nvarchar(max) to datetime format:
SELECT
CAST(PSCData._SUBMISSION_DATE AS DATETIME2)
FROM
PSCData
I have tried every possible way but still its giving this error:
Conversion failed when converting date and/or time from character string.
The data inside my _Submission_Date is in this form:
"2017-8-21 21:13:55.00000"
"2017-9-21 14:13:55.00000"
When I run this query it works fine:
SELECT CAST('2017-08-25' AS DATETIME);
but with this format :
SELECT CAST('2017-9-21 14:13:55.00000' AS DATETIME);
I get the same error mentioned above.
Any suggestions that how I can solve this?
Found the solution. The actual problem was the double quotes around the string which was causing the error it can be solved like this:
update PscData
SET _SUBMISSION_DATE = REPLACE(_SUBMISSION_DATE,'"', '')
select CAST(PSCData._SUBMISSION_DATE as DATETIME2)
FROM PSCData
i.e: first use the REPLACE method to remove double quotes around the string than you can use the cast method and can easily convert the "varchar" type data to "datetime" format without any problem. Plus u have to use "datetime2" in the cast method as "datetime" will not work with it.
Thanks for the help btw :)

Why is this DateTime.ParseExact statement not working?

The following line gives me a "String was not recognized by a valid DateTime" error:
DateTime.ParseExact("4/6/2016", "dd/MM/yyyy", Nothing)
I got this "working" example on stackoverflow, but it doesn't work for me: Parse Exact Sample and I can't figure out why.
EDIT (reedit, I mistakenly typed the last two attempts wrong):
Still no good. This is what I've found after trying all the suggestions submitted so far (thanks all). Some more info, the date string is coming from a textbox control.
Dim xxx As String = "4/6/2016" 'OR = "04/06/2016" as necessary for the sample
This does not work:
DateTime.ParseExact(xxx, "M/d/yyyy", CultureInfo.InvariantCulture)
This does not work:
DateTime.ParseExact(xxx, "MM/dd/yyyy", CultureInfo.InvariantCulture)
After, I tried something simpler with just DateTime.Parse:
DateTime.ParseExact(xxx)
I typed this out by hand. I did NOT use values from a textbox control and it DID work:
DateTime.Parse("4/6/‎2016‎")
So frustrating
Your format says you'll have two digits for the day and the month. Your actual values only have one digit.
You have two options:
Follow the format you've specified, e.g. 04/06/2016
Change the format to match the value, e.g. d/M/yyyy
Additionally - and separately - you're passing in Nothing as the format provider, which means the current culture will be used. Your format uses / which is the culture-specific date separator. If your current culture doesn't use / as its date separator, that's another problem. If you've got a fixed format, you probably want to specify CultureInfo.InvariantCulture as the format specifier instead.
Here's a short but complete program demonstrating it working:
Option Strict On
Imports System
Imports System.Globalization
Public Class Test
Shared Sub Main()
Dim xxx As String = "4/6/2016"
Dim result as DateTime = DateTime.ParseExact(xxx, "M/d/yyyy", CultureInfo.InvariantCulture)
Console.WriteLine(result)
End Sub
End Class
When you use dd or MM it expects a two digit number, so you would need to use "04/06/2016" or else replace them with their single digit versions of d and M.

Resources