简体   繁体   中英

Date formatting - making dd/m/yyyy into dd/mm/yyyy

I got a pretty simple question (but yet I've been stuck at it for some time now). Does anyone know how to make the date value from dd/m/yyyy into dd/mm/yyyy in a variable?

dim lastdaylastmonth as date

lastdaylastmonth = DateSerial(Year(Date), Month(Date), 0)

So this code, as of now, would return the last day of last month, so it will be 31/5/2015. For the sake of formatting, and a MID() down along the code to pull out the month string "05", I will need to convert the date to dd/mm/yyyy or 31/05/2015. Does anyone know the simple solution for this? I've tried:

lastdaylastmonth = format(DateSerial(Year(Date), Month(Date), 0), "dd/mm/yyyy")

and it still returns the same value! Any heroes out there? :D

Use String

Sub dural()
    Dim lastdaylastmonth As String
    lastdaylastmonth = Format(DateSerial(Year(Date), Month(Date), 0), "dd/mm/yyyy")
    MsgBox lastdaylastmonth
End Sub

在此处输入图片说明

See this:

lastdaylastmonth = DateSerial(Year(Date), Month(Date), 0)
?lastdaylastmonth
31.05.2015 
? format(lastdaylastmonth,"dd.mm.yyyy")
31.05.2015
? format(lastdaylastmonth,"mm")
05  

The last output is a string, ready to be used in your code.

I prefer this method simply due to the fact that I have to deal with many different Excel versions around the world. Using format with "mm/dd/yyyy" will only work in the US (or whereever English is the defined language). In other counries the below code will still work.

Dim lastdaylastmonth As Date

'Last day of last month
lastdaylastmonth = Date - Day(Date) - 1

'Formatting it US-style regardless of international Excel or Windows settings
Debug.Print Right("0" & Day(lastdaylastmonth), 2) & "/" & Right("0" & Month(lastdaylastmonth), 2) & "/" & Year(lastdaylastmonth)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM