Get current time in milliseconds, or HH:MM:SS:MMM format
This is a cleaner solution using HowardHinnant's date library.
std::string get_time()
{
using namespace std::chrono;
auto now = time_point_cast<milliseconds>(system_clock::now());
return date::format("%T", now);
}
How to convert time from hh:mm:ss.mmm to seconds and milliseconds mysql
This should do what you're asking, if I understand correctly you already have the data containing milliseconds.
I don't think MySQL has an inherent millisecond function, but we can use microseconds instead.
SELECT CONCAT(TIME_TO_SEC('15:30:15.293'), '.', TIME_FORMAT('15:30:15.293', '%f'));
This will output as below;
55815.293000
How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
How to convert millisecond (uint64) into HH:MM:SS,MMM format in Go
Using the time
package
If the duration is less than a day, you may simply add it to a reference timestamp having zero time part, then format the time using a proper layout.
The reference time may be the zero value of time.Time
or the unix reference time.
For example:
ms := int64(65104)
var t time.Time // Zero time
t = t.Add(time.Duration(ms) * time.Millisecond)
fmt.Println(t.Format("15:04:05,000"))
t = time.UnixMilli(ms)
fmt.Println(t.Format("15:04:05,000"))
This will output (try it on the Go Playground):
00:01:05,104
00:01:05,104
If you want to handle durations bigger than a day, this solution is not suitable. A possible solution is to calculate hours yourself, and use the above method for the rest (minutes, seconds, milliseconds).
For example:
const msInHour = 60 * 60 * 1000
func format(ms int64) string {
hours := ms / msInHour
ms = ms % msInHour
t := time.UnixMilli(ms)
return fmt.Sprintf("%02d:%s", hours, t.Format("04:05,000"))
}
Testing it:
fmt.Println(format(65104))
fmt.Println(format(27*60*60*1000 + 65104))
This will output (try it on the Go Playground):
00:01:05,104
27:01:05,104
Rolling your own solution
If you don't want to use the time
package, you can do it yourself. The algorithm is simply divisions and remainers. E.g. the millisecond part is the remainder after dividing by 1000. The seconds after this is the remainder after dividing by 60 etc.
For example:
func format(n int64) string {
ms := n % 1000
n /= 1000
sec := n % 60
n /= 60
min := n % 60
n = n / 60
return fmt.Sprintf("%02d:%02d:%02d,%03d", n, min, sec, ms)
}
This also handles durations greater than a day. Testing it:
fmt.Println(format(65104))
fmt.Println(format(27*60*60*1000 + 65104))
This will output (try it on the Go Playground):
00:01:05,104
27:01:05,104
How to convert milliseconds to hh:mm:ss format?
You were really close:
String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)), // The change is in this line
TimeUnit.MILLISECONDS.toSeconds(millis) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
You were converting hours to millisseconds using minutes instead of hours.
BTW, I like your use of the TimeUnit
API :)
Here's some test code:
public static void main(String[] args) throws ParseException {
long millis = 3600000;
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
System.out.println(hms);
}
Output:
01:00:00
I realised that my code above can be greatly simplified by using a modulus division instead of subtraction:
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
Still using the TimeUnit
API for all magic values, and gives exactly the same output.
format date (received in milliseconds) in yyyy-mm-dd hh-mm in jquery/javascript [duplicate]
Short and Sweetttt....
var myDate = new Date(1559736267189);alert(myDate.getFullYear() + '-' +('0' + (myDate.getMonth()+1)).slice(-2)+ '-' + ('0' + myDate.getDate()).slice(-2) + ' '+myDate.getHours()+ ':'+('0' + (myDate.getMinutes())).slice(-2)+ ':'+myDate.getSeconds());
Convert yyyy-MM-dd'T'HH:mm:ss.mmm'Z' to normal HH:mm a format
The first thing is that you're using mm:ss.mmm
in your format. According to SimpleDateFormat
javadoc, m
represents the minutes, so you must change it to mm:ss.SSS
because S
represents the milliseconds.
Another detail is that the Z
in the end is the timezone designator for UTC and it can't be ignored (at least it shouldn't). You must use the corresponding pattern for that, which is X
:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Date date = sdf.parse("2017-08-02T06:05:30.000Z");
PS: the X
pattern was introduced in Java 7. If you're using Java <= 6, the only alternative is to treat Z
as a literal (an ugly workaround, I admit) and set the UTC as the timezone used by the parser:
// treat "Z" as literal
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// use UTC as timezone
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2017-08-02T06:05:30.000Z");
With this, the date will have the value corresponding to 06:05 in UTC. To format the time to your timezone, you must use another SimpleDateFormat
with the corresponding timezone:
// output format: hour:minute AM/PM
SimpleDateFormat outputFormat = new SimpleDateFormat("hh:mm a", Locale.ENGLISH);
// assuming a timezone in India
outputFormat.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
System.out.println(outputFormat.format(date));
The output will be:
11:35 AM
If you don't set a timezone, it'll use the system's default. But the default can be changed without notice, even at runtime, so it's better to explicity set a specific timezone as above.
I also used java.util.Locale
to set the language to English, because some locales can have different symbols for AM/PM. If you don't specify one, it'll use the system default and it's not guaranteed to be one in which the symbols are the ones you need (some locales uses "a.m./p.m." or another different formats, so it's better to use an explicit locale).
Java new Date/Time API
The old classes (Date
, Calendar
and SimpleDateFormat
) have lots of problems and design issues, and they're being replaced by the new APIs.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time
and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp
), but the classes and methods names are the same.
To parse the input you can use the ZonedDateTime
class, which has full support to timezones and it makes the conversion to another zones very easy. Then you use a DateTimeFormatter
to format the output:
// parse the input
ZonedDateTime parsed = ZonedDateTime.parse("2017-08-02T06:05:30.000Z");
// convert to another timezone
ZonedDateTime z = parsed.withZoneSameInstant(ZoneId.of("Asia/Kolkata"));
// format output
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
System.out.println(fmt.format(z));
The output will be:
11:35 AM
If the input always has Z
in the end, you can also use the Instant
class:
// parse the input
Instant instant = Instant.parse("2017-08-02T06:05:30.000Z");
// convert to a timezone
ZonedDateTime z = instant.atZone(ZoneId.of("Asia/Kolkata"));
Note that I used hh
for the hours: this will format using values from 1 to 12 (it makes sense because I'm also using the AM/PM designators). If you want values from 0 to 23, use HH
instead - check the javadoc for more details.
Also note that the API uses IANA timezones names (always in the format Region/City
, like Asia/Kolkata
or Europe/Berlin
).
Avoid using the 3-letter abbreviations (like CST
or IST
) because they are ambiguous and not standard.
You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds()
.
You can also use the system's default timezone with ZoneId.systemDefault()
, but this can be changed without notice, even at runtime, so it's better to explicity use a specific one.
Related Topics
Is There a Performance Difference Between I++ and ++I in C++
What Are the Rules For Calling the Base Class Constructor
Variable Number of Arguments in C++
How to Create a Contiguous 2D Array in C++
Array Index Out of Bound Behavior
How to Stop C++ Console Application from Exiting Immediately
Best Practices For Circular Shift (Rotate) Operations in C++
What Is the Type of String Literals in C and C++
How to Convert Between Big-Endian and Little-Endian Values in C++
Difference Between G++ and Gcc
How Do Malloc() and Free() Work
C++ Unordered_Map Using a Custom Class Type as the Key
Why Do Function Pointer Definitions Work With Any Number of Ampersands '&' or Asterisks '*'
#Pragma Once VS Include Guards