Why is this DateTime.ParseExact statement not working? - asp.net

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.

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)

ISO datetime with timezone issue

I am just printing the ISO datetime with timezone as per the below documentation
http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a003169814.htm
This is my code
TimeZone tz = TimeZone.getTimeZone("UTC");
DateFormat df = new SimpleDateFormat("yyyy-mm-dd'T'hh:mm:ss.nnnnnn+|-hh:mm");
df.setTimeZone(tz);
dateTimeWithTimeZone = df.format(new Date());
However i am getting this exception
Illegal pattern character 'n'
I cant use this format directly in Java ?
java.time
dateTimeWithTimeZone = Instant.now().toString();
System.out.println(dateTimeWithTimeZone);
When I ran this snippet just now, I got this output:
2019-03-18T22:28:13.549319Z
It’s not clear from the page you link to, but it’s an ISO 8601 string in UTC, so should be all that you need. I am taking advantage of the fact that the classes of java.time produce ISO 8601 output from their toString methods. The linked page does show the format with hyphens, T and colons (2008-09-15T15:53:00+05:00), it shows another example with decimals on the seconds (15:53:00.322348) and a third one with Z meaning UTC (20080915T155300Z), so I would expect that the combination of all three of these would be OK too.
The format you used in the quesiton seems to try to get the offset as +00:00 rather than Z. If this is a requirement, it’s only a little bit more complicated. We are using an explicit formatter to control the variations within ISO 8601:
DateTimeFormatter iso8601Formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxx");
dateTimeWithTimeZone = OffsetDateTime.now(ZoneOffset.UTC).format(iso8601Formatter);
System.out.println(dateTimeWithTimeZone);
2019-03-18T22:28:13.729711+00:00
What went wrong in your code?
You tried to use the formatting symbols from your source with SimpleDateFormat. First, you should never, and especially not in Java 8 or later, want to use SimpleDateFormat. That class is notoriously troublesome and long outdated. Second, some of its format pattern letters agree with the symbols from your source, some of them don’t, so you cannot just use the symvol string from there. Instead you need to read the documentation and find the correct format pattern letters to use for year, month, etc. And be aware that they are case sensitive: MM and mm are different.
Link
Oracle Tutorial: Date Time
explaining how to use java.time.

MSACCESS Form VBA Open Where Clause - US v AU Date Formatting

Morning all,
This should be a simple fix and I have searched around and found things that appear they should work, but they don't seem to though...
So - it's a simple "Open this form and show only records from This date" function and, you guessed it, good ol' US of A date formatting is the problem and no matter which way I try it nothing is solving the problem...
So - here's the form code...
DoCmd.OpenForm "frm_Prod_Runs_Edit_List", , , "# " & NEWDATE & " #"
to find NEWDATE...
I strip the date components from a couple of combo boxes (CBOYear & CBOMonth) and a field that represents the day of the month (data will be in the format "1st" or "2nd" etc...)
I concatenate the individual components...
NEWDATE = DateSerial(TempYear, TempMonth, TempDate)
A msgbox NEWDATE popup results in the correct data (ie 1/3/18)
But when I run the code it either selects everything or nothing... the only time the function works is when the day field is 13 or higher (ie 13/3/18) - thus it can determine the correct format to work with.
I'm sure the correct answer is already here somewhere - the correct question however may be something I have not thought to search for.
I have tried to use DATEVALUE() before and within the form open code. I have tried to hard code the US format to see if that works...
DoCmd.OpenForm "frm_Prod_Runs_Edit_List", , , "#3/1/18#"
No good... shows all records - same if I hard code for the AU format #1/3/18#
My PC is set up for AU format dd/mm/yy
So... Which function do I need to use to convert the AU Date string into US Date string prior to calling the Openform, so the correct records open? OR is there a better way to write the WHERE clause in the Docmd line to achieve this result? - Or do I need to reset all my date fields to US format and convert them back to AU on the forms only?
Thanks for the feedback...
In VBA and VB6, date-literals using the # syntax are always in M/dd/yyyy format, regardless of the user's date format settings. This is a legacy of VBA/VB6's development in the USA before localization was a concern (and the USA is the only country to use the illogical MM/dd/yyyy format).
Note it's M/dd/yyyy and not MM/dd/yyyy - so omit any leading zeroes.
This is documented here: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/data-types/date-data-type
The same rule also applies to date-literals in Access SQL (not the same thing as VBA/VB6). Fortunately in SQL Server you always use the ISO 8601 yyyy-MM-dd format in quotes... shame about Access though.
You simply need a properly formatted string expression for your date value - and the correct syntax:
Dim NEWDATE As Date
Dim WhereCondition As String
NEWDATE = DateSerial(TempYear, TempMonth, TempDate)
WhereCondition = "[NameOfYourDateField] = #" & Format(NEWDATE, "yyyy\/mm\/dd") & "#"
DoCmd.OpenForm "frm_Prod_Runs_Edit_List", , , WhereCondition
Your first problem is that you're not comparing NewDate to something.
Your second problem is that you're using string concatenation to filter by a date, and that results in the wrong date.
You can view this answer for the different ways to use parameters in Access.
Your final code should probably look something like this:
NEWDATE = DateSerial(TempYear, TempMonth, TempDate)
DoCmd.SetParameter("NewDateParam", NEWDATE)
DoCmd.OpenForm "frm_Prod_Runs_Edit_List", , , "SomeDateField = NewDateParam"
Or, if there might be time stored with the date:
NEWDATE = DateSerial(TempYear, TempMonth, TempDate)
DoCmd.SetParameter("NewDateParam", NEWDATE)
DoCmd.OpenForm "frm_Prod_Runs_Edit_List", , , "SomeDateField - NewDateParam < 1"

ASP.Net VB string to date based on format used in string

I'm using a JavaScript datepicker that gives me the selected date based on the language. So when the language is Dutch I get an output like 21-09-2017 (dd-mm-yyyy) And for English 21/09/2017.
When I want to cast these Strings to Dates (CDate) I get a problem with the format. Day = Month or Month = Day. What is the best way to make a Date from a string based on the format used in the string?
A solution would be to write a function for each specific culture to handle the dates but i'm guessing there is a default function in .Net??
You can use DateTime.ParseExact to get what you want as shown here.
You can provide the format like so:
dateString = "15/06/2008 08:30" //Your Date time
format = "g" //General Fromat
provider = New CultureInfo("fr-FR") //French
result = Date.ParseExact(dateString, format, provider) //Parsed Result
this will result in: 6/15/2008 8:30:00 AM
This or course only works if you know the culture. Also you may want to check out the Date Time Format Strings found here.
Convert.ToDateTime(String).ToString("dd-MM-yyyy")
OR
DateTime.ParseExact(String, "dd/MM/yyyy", CultureInfo.InvariantCulture)

Applescript: Convert date into something useful, then perform calculation

I'm trying to create an applescript script that will take a date in the form:
02/20/99
Then, subtract 5 days from the date, and return a date like this:
02/15/99
Here's the basic applescript I have, but, obviously, I'm missing the logic around converting the date into something that I can manipulate (and returning it to something readable by humans).
set itemPath to quoted form of POSIX path of theFile
set dateString to do shell script "awk 'NR == 10 {print $3}' " & itemPath & " -"
set myDueDate to dateString - (5 * days)
set theTask to "Pay AMEX bill"
tell application "OmniFocus"
tell front document
set theContext to first flattened context where its name = "OFFICE"
set theProject to first flattened context where its name = "Bookkeeping - PMS"
tell theProject to make new task with properties {name:theTask, context:theContext, due date:myDueDate}
end tell
end tell
Thanks in advance!
I think these lines should be sufficient for what you need:
set dateString to "02/20/99"
set thisDate to date dateString
set fiveDaysEarlier to thisDate - 5 * days
log date string of fiveDaysEarlier
log short date string of fiveDaysEarlier
This page has some more examples of the coercions supported when converting strings to objects of date class:
AppleScript Class Reference: date
Also, it probably goes without saying, but the string "02/20/99" is not Y2k compliant, so guesses will have to be made somewhere as to which century this date lies in.
If you get error "FileMaker Pro got an error: Object not found." number -1728, add my before date. e.g,
set thisDate to my date dateString.
When working inside a tell, I think it needs to access methods outside the tell's scope.

Resources