2

How to find 'last SUNDAY DATE' through batch command? what I was trying is

echo %date:~4,2%%date:~7,2%%date:~10,4%

this is good for current date but for last Sunday date... can anyone suggest any logic through batch.

Asmi
  • 365
  • 6
  • 21
Rahul Patel
  • 307
  • 1
  • 9
  • 27
  • 2
    To get add/sub functionallity for dates try a look at [How to get yesterday's date in batch file?](http://stackoverflow.com/questions/23010670/how-to-get-yesterdays-date-in-batch-file) – jeb Nov 18 '15 at 08:34

1 Answers1

3

Windows PowerShell:

[DateTime]::Now.AddDays(-1 * [DateTime]::Now.DayOfWeek.value__)

Sorry the environment variable %date% in Batch (.bat) files sounds uneasy to do calculations.

Ken Cheung
  • 1,778
  • 14
  • 13
  • @jeb Thanks and I have removed Linux and OSX part because I mis-reach batch to bash initially and only recognize batch-file refers to DOS .bat. In order to have at least an answer for Microsoft's platform, I've put PowerShell as replacement. – Ken Cheung Nov 18 '15 at 08:36
  • Thanks a lot ken, it worked as i expected. I used powershell [DateTime]::Now.AddDays(-1 * [DateTime]::Now.DayOfWeek.value__) ... Now how do i store output into variable. – Rahul Patel Nov 18 '15 at 13:43
  • By "store output into variable" do you mean a BATCH file variable? That's tricky. The simplest thing is to write your whole script in Powershell. However if that's not an option you could have the PS script return a return code that's the date of last Sunday. So if last Sunday is on 15th then return code = 15. But if last Sunday is in previous month you'd have to do something special. If return codes could be negative you could return -1 for last day of previous month. But return codes must be positive, so instead add, say, 40, so 39 is last day of previous month. 38 is next to last day, etc. – Χpẘ Nov 18 '15 at 22:04
  • Thanks guys i got it. – Rahul Patel Nov 29 '15 at 09:59
  • Great solution; you don't need the `.value__` part, because the `[System.DayOfWeek]` enumeration value returned by `[DateTime]::Now.DayOfWeek` is implicitly converted to its integer equivalent in this case. – mklement0 Feb 25 '16 at 04:41