Get WeekNumber of Month from varchar date provided

Nody88 1 Reputation point
2020-08-27T14:44:37.677+00:00

Hi I need to get Week number (in a month i.e 1/2/3 Not week in year)of a particular datetime.

I am trying to get weeknumber

example varchar datatype datetime values as below

'19/08/20 07:23:42'

'03/08/20 09:28:09'

Note i tried online solutions but any functions datepart/format/conver/cast is failing on the value '19/08/20 07:23:42' but works fine for '03/08/20 09:28:09'

Please provide a Generic solution to get WeekNumber of Month for any given date value along with proper convert etc function ASAP.

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,808 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,558 questions
{count} votes

6 answers

Sort by: Most helpful
  1. Jeff Moden 11 Reputation points
    2022-06-20T05:16:42.847+00:00

    Just temporarily change the session-level date format like this...

    --===== This simulates the issue the OP described.  
      PRINT 'Using MDY...';  
        SET DATEFORMAT MDY --Session level setting here.  
    ;  
     SELECT CONVERT(DATETIME,'19/08/20 07:23:42'); --This fails.  
    ;  
    GO  
      PRINT REPLICATE('-',119);  
    GO  
    --===== This is the simple fix within a proc  
      PRINT 'Using DMY for the session level setting...';  
      PRINT 'Doe NOT change the server level setting!'  
    ;  
        SET DATEFORMAT DMY --Session level setting here.  
    ;  
     SELECT CONVERT(DATETIME,'19/08/20 07:23:42'); --Now it works.  
    ;  
    GO  
    

    See the following link for more information.
    REF: https://learn.microsoft.com/en-us/sql/t-sql/statements/set-statements-transact-sql

    0 comments No comments