Extract Time from Date String

Extract time from date String

Use DateTimeFormatter to convert between a date string and a real LocalDateTime object. with a LocalDateTime as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the DateTimeFormatter.

String originalString = "2010-07-14 09:00:02";
LocalDateTime dateTime = LocalDateTime.parse(originalString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String newString = DateTimeFormatter.ofPattern("H:mm").format(dateTime); // 9:00

In case you're not on Java 8 or newer yet, use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat.

String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00

How to extract time from date string in javascript?

Try this:

new Date().toISOString().split('T')[1].split('.')[0];

How to extract date and time from a String Timestamp in java

Use java.text.SimpleDateFormat and java.util.TimeZone

Which timezone the date string is in? Replace the below UTC timezone with that timezone

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2014-02-15 05:18:08");

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
sdf2.setTimeZone(TimeZone.getTimeZone("IST"));
String dateStr = sdf2.format(date); // Output: 15-02-2014 10:48:08 AM

Note: In which format the hour is in (24 hour/ 12 hour) in your input string? The above example assumes that it is in 24 hour format because there in no AM/PM info in the input string.

If the input string is also in 12 hour format then your input string should mention AM/PM info also such as 2014-02-15 05:18:08 PM. In that case, modify the sdf to new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a")

========================
Edited: =====================

To answer your next question in comment "How to extract date and time separately"...

SimpleDateFormat sdfDate = new SimpleDateFormat("dd-MM-yyyy");
sdfDate.setTimeZone(java.util.TimeZone.getTimeZone("IST"));

SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm:ss a");
sdfTime.setTimeZone(java.util.TimeZone.getTimeZone("IST"));

String dateStr = sdfDate.format(date);
String timeStr = sdfTime.format(date);

Extract from string information on date/time

If the format stays simple : <digits> <unit> ago ... it's pretty to parse with "^(\d+) (\w+) ago".

Then, once you have ('minutes', '12') you'll pass these to timedelta which accepts every unit as a keyword argument timedelta(minutes=12), you'll do that by passing a mapping **{unit:value}

def parse(content):
timeparts = re.search(r"^(\d+) (\w+) ago", content)
if not timeparts:
return None, content
unit = timeparts.group(2).rstrip('s') + 's' # ensure ends with 's'
#return datetime.now()-timedelta(**{unit:int(timeparts.group(1))}) # Now date
return datetime(2020,5,26,8,0,0)-timedelta(**{unit:int(timeparts.group(1))}) # Fixed date

Demo

values = ["12 minutes ago - There was a meeting...","2 hours ago - Apologies for being...","1 day ago - It is a sunny day in London..."]

for value in values:
res = parse(value)
print(res)

2020-05-26 07:48:00
2020-05-26 06:00:00
2020-05-25 08:00:00

Extract time from date time and find difference between 2 times

In PowerShell, you'd usually use a format string. Subtracting two PowerShell datetimes returns a value of type Timespan, which is well-behaved over a span of more than 24 hours.

([datetime]"12 October 2021 21:16:04" - [datetime]"12 October 2021 07:46:46") -f "HH:mm:ss"
13:29:18

Be careful here. Both intervals (durations) and time (of day) have the same format, but different meanings. For example, it makes sense to multiply the interval "01:00:00" (1 hour) by 3 to get three hours; it doesn't make sense to multiply the time "01:00:00" (1 o'clock AM) by 3.

I'm sure the overall calculation can be simplified, but it's too early for me.

Kotlin extract time form the date

One of the RECOMMENDED WAYs

In case you can use java.time, here's a commented example:

import java.time.LocalDateTime
import java.time.LocalDate
import java.time.format.DateTimeFormatter

fun main() {
// example String
val input = "2027-02-14T14:20:00.000"
// directly parse it to a LocalDateTime
val localDateTime = LocalDateTime.parse(input)
// print the (intermediate!) result
println(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
// then extract the date part
val localDate = localDateTime.toLocalDate()
// print that
println(localDate)
}

This outputs 2 values, the intermediate LocalDateTime parsed and the extracted LocalDate (the latter simply invoking its toString() method implicitly):

2027-02-14T14:20:00
2027-02-14


NOT RECOMMENDED but still possible:

Still use the outdated API (might be necessary when it comes to large amounts of legacy code, which I doubt you will find written in Kotlin):

import java.text.SimpleDateFormat

fun main() {
val firstDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
.parse("2027-02-14T14:20:00.000")
val firstTime = SimpleDateFormat("yyyy-MM-dd").format(firstDate)
println(firstTime)
}

Output:

2027-02-14

Extract hour from timestamp in string format on bigQuery

First you need to cast string as timestamp and then need to extract hour.
I have replicated issue in my project and here is the solution.

Query part- ( ts_string is column name with string datatype)
EXTRACT(hour
FROM
CAST(ts_string AS timestamp)) AS hour_extracted
Sample Image

Is there any way to Extract time string from UTC time in Javascript

So, I couldn't find any other method more appealing than mine :)

var date = new Date('Sat, 19 Jan 2019 05:40:07 GMT'); console.log(date.toISOString().split("T")[1].split(".")[0]);

extract date and time from String object android

You can try this way

 String strDateTimeBoj="Oct 11 2014 5:30PM";
//first you need to use proper date formatter
DateFormat df=new SimpleDateFormat("MMM dd yyyy hh:mmaa");
Date date=df.parse(strDateTimeBoj);// converting String to date
System.out.println(df.format(date));

Out put:

 Oct 11 2014 05:30PM

Which date format should I use?

You can find it out by your own by read this.

Edit

you can use before() after() method to compare dates.

Date today=new Date();

System.out.println(today.after(date));
System.out.println(today.before(date));

Out put:

false
true


Related Topics



Leave a reply



Submit