I have a column fecha formatted as a string in the form of
Mon Feb 22 07:55:55 CET 2021
How do I convert it to a date format like YYYY-MM-DD? I have tried CAST, CONVERT ...
And I always get the following error message:
Msg 241, Level 16, State 1, Line 4
Conversion failed when converting date and/or time from character string
Assuming, as I comment, the value is always ddd MMM dd hh:mm:ss tz yyyy you could do some messy string manipulation to convert the value to a valid date and time data type. Then you can format the date however you want in your presentation layer, as it's strongly typed:
SELECT V.DateString,
TRY_CONVERT(datetime2(0),STUFF(STUFF(LEFT(STUFF(V.DateString,1,8,''),12),3,0,RIGHT(V.DateString,5)),3,0,SUBSTRING(V.DateString,4,4)),113) AS ConvertedDate
FROM (VALUES('Mon Feb 22 07:55:55 CET 2021'))V(DateString);
Of course, the real lesson here is don't store date and time values as a varchar in your database. Date and Time data types exist for a reason; use them.
I don't think there are standard functions to deal with your source strings, so I would combine simpler standard transformations to get that result :
declare #Cadena varchar(50) = 'Mon Feb 22 07:55:55 CET 2021'
select substring(#Cadena, 25, 4) + '-' +
replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(substring(#Cadena, 5, 3), 'Jan', '01'), 'Feb', '02'), 'Mar', '03'), 'Apr', '04'), 'May', '05'), 'Jun', '06'), 'Jul', '07'), 'Aug', '08'), 'Sep', '09'), 'Oct', '10'), 'Nov', '11'), 'Dec', '12') + '-' +
substring(#Cadena, 9, 2)
This will fail if your string are not always in the exact same format, in that case more code would be needed.
Related
I have a string that I want to convert into a date to compare it to the current date and hour (local time). The string format is like this:
2020-06-09 11:25 pm
And I want to use either Date or Moment.js to format it to a Date object, but so far I haven't had any luck.
const date = new Date(`${eventDayFinish} ${eventHourFinish}`);
Prints Date { NaN }
Any help will be appreciated.
Use the moment this way.
let d = moment('2020-06-09 11:25 pm', 'YYYY-MM-DD HH:mm a').format();
console.log(new Date(d));
// Tue Jun 09 2020 23:25:00 GMT+0530 (India Standard Time)
Explanation:
Moment takes the second argument as the format of the input date string, you can give any format to it, along with the format you passed, it will return you the date object.
I've inherited quite a mess of a database table column called DOB, of type nvarchar - here is just a sample of the data in this column:
DOB: 1998-09-04US
Sex: M Race: White Year of Birth: 1950
12/31/00
January 5th, 1998
Date of Birth: 12/19/1938
AGE; 46
DOB: 11-24-1967
May 31, 1942, Split, Croatia
DOB:   12/28/1986
D.O.B.31-OCT-92
D.O.B.: January 8, 1973
31/07/1974 (44 years old)
Date Of Birth: 08/01/1979
78  (DOB: 12/09/1940)
1961 (56 years old)
12/31/1985 (PRIMARY)
DOB: 05/27/67
8-Jun-43
9/9/78
12/31/84 0:00
NA
Birth Year 2018
nacido el 29 de junio de 1959
I am trying to determine whether there is any way to extract the dates from these fields, with so many varying formats, without using something like RegEx patterns for every single possible variation in this column.
The resulting extracted data would look like this:
1998-09-04
1950
12/31/00
January 5th, 1998
12/19/1938
11-24-1967
May 31, 1942
12/28/1986
31-OCT-92
January 8, 1973
31/07/1974
08/01/1979
12/09/1940
1961
12/31/1985
05/27/67
8-Jun-43
9/9/78
12/31/84
NA
2018
29 de junio de 1959
While it may be a complete pipe dream, I was wondering if this could be accomplished with SQL, with some kind of "if it looks like a date, attempt to extract it" method. And if not out-of-the-box, perhaps with a helper extension or plugin?
It is possible, but there are potential pitfalls. This will certainly have to be expanded and maintained.
This is a brute-force pattern match where the longest matching pattern is selected
Example - See Full Working Demo
Select ID
,DOB
,Found
From (
Select *
,Found = substring(DOB,patindex(PatIdx,DOB),PatLen)
,RN = Row_Number() over (Partition By ID Order by PatLen Desc)
From #YourTable A
Left Join (
Select *
,PatIdx = '%'+replace(replace(Pattern, 'A', '[A-Z]'), '0', '[0-9]') +'%'
,PatLen = len(Pattern)
From #FindPattern
) B
on patindex(PatIdx,DOB)>0
) A
Where RN=1
Returns
In my T-SQL select there appears to be an error with my datetime
select
t.F47, t.F53, t.F40, t.F162, t.F163,
N'10' as kostenart, t.F39, t.F2, t.F5,
convert(nvarchar, cast(t.F9 as datetime), 112),
t.PARID, 20170928135800 as exportzeitstempel
from
T_TRANS6 as t
where
t.F20 = N'Erledigt'
and t.F9 < convert(datetime, '01.09.2017 00:00:00', 104)
The error message is German and it says:
Meldung 242, Ebene 16, Status 3, Zeile 1
Bei der Konvertierung eines nvarchar-Datentyps in einen datetime-Datentyp liegt der Wert außerhalb des gültigen Bereichs.
I tried to translate this to:
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value."
I really don't know how I did from so thanks for any help guys
Your problem is triggered by cast(t.F9 as datetime).
Please do : SELECT getdate(); to get the implicit "datetime to string" convertion format.
WARNING : Implicit convertion format are set at the instance level. It can differ from a server to another, even in the same compagny...
This will gives you someting like dd.MM.yyyy HH:mm:ss or yyyy-MM-dd HH:mm:ss or ...
The given format is the one expected and required for all F9 of TRANS6 table records!!
A single TRANS6.F9 with a wrong formating patern will raise this ERROR. So analyse your F9 data, find the concerned rows, clean them and retry...
NOTE : CONVERT(NVARCHAR(8), getdate(),112) get a string like YYYYMMDD (Ex : '20170928') witch is the only sortable string format of dates...
EDIT : F9 = '2016.10.30' and Implicit convertion expect '2016-10-30' !!
Try this :
select
t.F47, t.F53, t.F40, t.F162, t.F163,
N'10' as kostenart, t.F39, t.F2, t.F5,
convert(nvarchar, convert(datetime,t.F9,102), 112),
t.PARID, 20170928135800 as exportzeitstempel
from
T_TRANS6 as t
where
t.F20 = N'Erledigt'
and t.F9 < convert(datetime, '01.09.2017 00:00:00', 104)
Does it works?
I have a database which keeps dates as a number like 1488950859, and when I run the software which associated to the DB, it shows this date : 2017-March 08 08:27 AM
another example is :
1395208154 = 2014 March 19, 8:49 AM
anyone can give me a hand and reveal this mysterious format?
I think you are storing date in a column of type nvarchar because when you save date in nvarchar column it converts into number.
I got it..
this is called Unix timestamp, it is no. of seconds since standard epoch of 1st Jan 1970.
to return it to ordinary date format , use below function
Public Function UnixToDateTime(ByVal strUnixTime As String) As DateTime
Dim nTimestamp As Double = strUnixTime
Dim nDateTime As System.DateTime = New System.DateTime(1970, 1, 1, 0, 0, 0, 0)
nDateTime = nDateTime.AddSeconds(nTimestamp)
Return nDateTime
End Function
i use angularjs and i want parse a string to a date my code looks like this:
var d=moment.utc("2011-10-02T22:00:00.000Z", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
var year =d.year();
var month =d.month();
var day =d.day();
$log.log("MOMENTS:"+"year: "+year+" month: "+month+" day: "+day);
the date should be "3 october 2011"
but in the log is :MOMENTS:year: 2014 month: 2 day: 6
this date is completly wrong, why is this so and what do i wrong ? i want extract the day, month and year
Here is a fiddle: http://jsfiddle.net/FGa2J/
moment.day() returns the day of the week (not the day of the month) you need moment.date() for that. moment.month() is 0 based, so you will get 9 for October. Also, it seems like moment can parse your date string just fine without specifying the format.
Code from the fiddle:
report ( "2011-10-02T22:00:00.000Z", ["yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"] );
var d = moment("2011-10-02T22:00:00.000Z");
var year = d.year();
var month = d.month();
var day = d.date();
console.log("MOMENTS:"+"year: "+year+" month: "+(month+1)+" day: "+day);
function report( dateString, formats) {
$("#results").append (
$("<li>", { text:
dateString + " is valid: " + moment(dateString, formats).isValid()
})
);
}
You're not using the correct string formatting characters.
You have: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
In moment, it would be: "YYYY-MM-DDTHH:mm:ss.SSSZ"
Note that it's case sensitive, and doesn't necessarily match formats from other languages (.Net, PHP, etc).
However - since this is the ISO-8601 standard format, it is detected and supported automatically. You should simply omit that parameter.
From the documentation:
... Moment.js does detect if you are using an ISO-8601 string and will parse that correctly without a format string.