Extract / parse different date formats from a single string

studio

#1

Hi, I have a string var called prevDay that uses the following to establish the previous date (and it works fine):
datetime.Now.AddDays(-1).ToString(“dd-MM-yy”, system.Globalization.CultureInfo.InvariantCulture)

What i’d like to do is, using that prevDay variable output, interpret it a different way later on (without having to create another variable). For example, prevDay at the moment returns 04-10-17, how can i get the month & year only for example Oct-17 by parsing it?

I really don’t want to remove say the first 3 characters as I need the full date later on again… and rather than recreate the string i’d just like a simple formatting solution.

I tried DateTime.ParseExact(prevDay, “ddMMMyyyy”,System.Globalization.CultureInfo.InvariantCulture) however received an error advising that i couldn’t convert a date to a string. However, when i try to fix that by changing the type of my original string variable to a date, i receive an error which states “…disallows implicit conversions from string to date”.

Feel as though i’m going round in circles, so any help would be appreciated!

Thanks!


#2

Hey there.

You need to use a DateTime variable, then you’re good to go. Since you are using the previous day, you can use Now as your DateTime value.

Actually you might already have it in the first line you have because .ToString lets you format the text.
For example,
prevDay as DateTime = datetime.Now.AddDays(-1)
prevDay.ToString(“MM-dd-yy”)
prevDay.ToString(“MMM-dd”)
prevDay.ToString(“MM/dd/yyyy”)

I think that should work for you.
Also, you can use Month(prevDay), Day(prevDay), or Year(prevDay) to extract only that part if you want.

Hope that answers your question.

Thanks.


#3

That’s great - thank you!