Converting DATETIME to a human readable date - datetime

I'm trying to convert the DATETIME to something that people can actually use. This is the date:
2013-09-05 11:52:10
I'm using:
date("D, d M Y", '2013-09-05 11:52:10');
Is turning into:
Thu, 01 Jan 1970
Makes no sense to me.

You need to turn the date into a timestamp before passing it to date()
$time = strtotime('2013-09-05 11:52:10');
echo date("D, d M Y", $time);

Is this supposed to be PHP code? If so, the correct is
date("D, d M Y", strtotime('2013-09-05 11:52:10'));
If this has to do with MySql, the correct function to use is DATE_FORMAT (however, what you have is invalid MySql syntax). Please clarify.

PHP's date() function can only handle integer timestamp values; it can't process strings as input.
If you need to convert from one string date format to another, you should use the DateTime::CreateFromFormat() method:
$dateObj = DateTime::CreateFromFormat($inputString);
$outputString = $dateObj->Format('D, d M Y');
However, I would recommend writing your query to use MySQL's UNIX_TIMESTAMP() function to get the date into PHP as a numeric timestamp that PHP's date() function can handle:
MySQL:
SELECT UNIX_TIMESTAMP(yourDateField) as yourDateField_timestamp FROM yourTable ...
Then you can write PHP exactly as you wanted:
PHP:
$dateObj = date('D, d M Y', $row['yourDateField_timestamp']);

Related

format_datetime() in Kusto for datetime with minutes and secounds as 00

In the azure data explorer documentation, there is a lot of supported formats but not the one that i am looking for.
What I need is to format the datetime like "yyyy-MM-dd HH" to set the minutes and seconds as 0
Input datetime
2020-04-21T17:44:27.6825985Z
expected results
2020-04-21 17:00:00
you can use bin() to round down to the hour, and if you still need to remove the datetime parts lower than seconds, you can use substring() (or format_datetime()). e.g.:
print d = datetime(2020-04-21T17:44:27.6825985Z)
| extend h = bin(d, 1h)
| extend h2 = substring(h, 0, 19)
hmm, if you always just want the rest to be 0, can you just use string concatenation?
let d = datetime(2020-04-21T17:44:27.6825985Z);
print strcat(format_datetime(d, "yyyy-MM-dd HH"), ":00:00")
the above code will give you the result of
2020-04-21 17:00:00

LocalDate pattern that shows day as weekday

I search for a pattern which looks like this: Thu, 11. 05. 1999
So I tried this syntax:
String pattern = "DDD, dd. mm. uuuu";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
But it won't work. When trying to format a LocalDate I get java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: MinuteOfHour.
A look into the official documentation of Java explaining the format pattern syntax is always good:
E = day-of-week
M = month
m = minute
So you should try this pattern:
EEE, dd. MM. uuuu
And setting the locale explicitly to English is also a good idea.

R sprintf in sqldf's like

I would like to do a looping query in R using sqldf to that select all non-NULL X.1 variable with date "11/12/2015" and at 9AM. Example :
StartDate X.1
11/12/2015 09:14 A
11/12/2015 09:36
11/12/2015 09:54 A
The date is in variable that generated from other query
nullob<-0
dayminnull<-as.numeric(sqldf("SELECT substr(Min(StartDate),1,03)as hari from testes")) # this produce "11/12/2015"
for (i in 1 : 12){
dday<-mdy(dayminnull)+days(i) #go to next day
sqlsql <- sprintf("SELECT count([X.1]) FROM testes where StartDate like '% \%s 09: %'", dday)
x[i]<-sqldf(sqlsql)
nullob<-nullob+x[i]
}
And it comes with error : Error in sprintf("SELECT count([X.1]) FROM testes WHERE StartDate like '%%s 09%'", :
unrecognised format specification '%'
Please hellp. thank you in advance
It's not super clear in the documentation, but a % followed by a %, that is %%, is the way to tell sprintf to use a literal %. We can test this fairly easily:
sprintf("%% %s %%", "hi")
[1] "% hi %"
For your query string, this should work:
sprintf("SELECT count([X.1]) FROM testes where StartDate like '%% %s 09: %%'", dday)
From ?sprintf:
The string fmt contains normal characters, which are passed through to
the output string, and also conversion specifications which operate on
the arguments provided through .... The allowed conversion
specifications start with a % and end with one of the letters in the
set aAdifeEgGosxX%. These letters denote the following types:
... [Documentation on aAdifeEgGosxX]
%: Literal % (none of the extra formatting characters given below are permitted in this case).

Convert datetime string to a different datetime string in PowerShell v2

I have the following string which is pulled from an entry in a log file.
$d = "19/09/2014 22:41:27"
However, I need to convert it so that it is
2014-09-19 22:41:27
so that I can export it with other sections of the logfile into a MySQL database.
But I can't for the life of me find a way to do this. I was expecting to find something like set-dateFormat, which would simply re-map the components of the string, but it doesn't seem to exist.
I have tried various variations of the following:
$a = "19/09/2014 22:41:27"
$d = [datetime]::ParseExact($a, "dd/MM/yyyy hh:mm:ss", $null)
$e = "{0:yyyymmddhhmmss}" -f [datetime]$d
But everything returns the error:
String was not recognized as a valid DateTime.
What is the best way to get the format I need please?
A quick play around, with the help of a few other blogs provided the following, very similar to your own. There's probably a way to make it a little more streamlined, but it will create the datetime object you need. Manipulating the output after that should be straightforward.
$theDTString = "19/09/2014 22:41:27".toString()
$theDateTimeObject = ([datetime]::ParseExact($theDTString,"dd/MM/yyyy HH:mm:ss",$null))
$theDateTimeObject.year.toString() + "-" + $theDateTimeObject.month.toString() +"-"+
$theDateTimeObject.day.toString() + " " + $theDateTimeObject.Hour.toString() + ":" +$theDateTimeObject.Minute.toString() + ":" + $theDateTimeObject.Second.toString()
The identical answer to your original input is this:
$a = "19/09/2014 22:41:27"
$d = [datetime]::ParseExact($a, "dd/MM/yyyy HH:mm:ss", $null)
$e = "{0:yyyymmddhhmmss}" -f [datetime]$d
It was having an error trying to convert hour 22 as a 12 Hour format.

Groovy: How do you initialise and compare date/time values from different timezones?

I need to standardise and compare date/time fields that are in differnt timezones. eg How do you find the time difference between the following two times?...
"18-05-2012 09:29:41 +0800"
"18-05-2012 09:29:21 +0900"
What's the best way to initialise standard varaibles with the date/time?
The output needs to display the difference and normalised data in a timezone (eg +0100) that is different to the incoming values and different to the local environment.
Expected Output:
18-05-2012 02:29:41 +0100
18-05-2012 01:29:21 +0100
Difference: 01:00:20
import java.text.SimpleDateFormat
def dates = ["18-05-2012 09:29:41 +0800",
"18-05-2012 09:29:21 +0900"].collect{
new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z").parse(it)
}
def dayDiffFormatter = new SimpleDateFormat("HH:mm:ss")
dayDiffFormatter.setTimeZone(TimeZone.getTimeZone("UTC"))
println dates[0]
println dates[1]
println "Difference "+dayDiffFormatter.format(new Date(dates[0].time-dates[1].time))
wow. doesn't look readable, does it?
Or, use the JodaTime package
#Grab( 'joda-time:joda-time:2.1' )
import org.joda.time.*
import org.joda.time.format.*
String a = "18-05-2012 09:29:41 +0800"
String b = "18-05-2012 09:29:21 +0900"
DateTimeFormatter dtf = DateTimeFormat.forPattern( "dd-MM-yyyy HH:mm:ss Z" );
def start = dtf.parseDateTime( a )
def end = dtf.parseDateTime( b )
assert 1 == Hours.hoursBetween( end, start ).hours
Solution:
Groovy/Java Date objects are stored as the number of milliseconds after
1970 and so do not contain any timezone information directly
Use Date.parse method to initialise the new date to the specified format
Use SimpleDateFormat class to specify the required output format
Use SimpleDateFormat.setTimeZone to specifiy the timezone of the output
data
By using European/London timezone rather than GMT it will
automatically adjusts for day light savings time
See here for a full list of the options for date time patterns
-
import java.text.SimpleDateFormat
import java.text.DateFormat
//Initialise the dates by parsing to the specified format
Date timeDate1 = new Date().parse("dd-MM-yyyy HH:mm:ss Z","18-05-2012 09:29:41 +0800")
Date timeDate2 = new Date().parse("dd-MM-yyyy HH:mm:ss Z","18-05-2012 09:29:21 +0900")
DateFormat yearTimeformatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z")
DateFormat dayDifferenceFormatter= new SimpleDateFormat("HH:mm:ss") //All times differences will be less than a day
// The output should contain the format in UK time (including day light savings if necessary)
yearTimeformatter.setTimeZone(TimeZone.getTimeZone("Europe/London"))
// Set to UTC. This is to store only the difference so we don't want the formatter making further adjustments
dayDifferenceFormatter.setTimeZone(TimeZone.getTimeZone("UTC"))
// Calculate difference by first converting to the number of milliseconds
msDiff = timeDate1.getTime() - timeDate2.getTime()
Date differenceDate = new Date(msDiff)
println yearTimeformatter.format(timeDate1)
println yearTimeformatter.format(timeDate2)
println "Difference " + dayDifferenceFormatter.format(differenceDate)

Resources