I want to get the time with react-native-date-picker. So I set the mode as time. But this gives in this format, Here time is not correct too.
2023-01-25T16:50:53.467Z
This is my code,
<DatePicker
mode="time"
date={date}
modal
open={pickupTimeModal1}
onConfirm={time => console.log(time)}
onCancel={() => {
setPickupTimeModal1(false);
}}
/>
I think this library gives you an entire date string.
You can convert the date to a format that you like:
new Date(Date.parse("2023-01-25T16:50:53.467Z")).toLocaleString();
// 1/25/2023, 8:50:53 PM
new Date(Date.parse("2023-01-25T16:50:53.467Z")).toLocaleDateString();
// 1/25/2023
new Date(Date.parse("2023-01-25T16:50:53.467Z")).toLocaleTimeString();
//8:50:53 PM
for better conversion, you can also use date-fns
let d = new Date();
let hours = d.getHours();
let minutes = d.getMinutes();
let seconds = d.getSeconds() <= 9 ? `0${d.getSeconds()}` : d.getSeconds();
console.log(`${hours}:${minutes}:${seconds}`);
Related
I have a date in UTC in javascript, and I would like to substract some hours.
I searched online and apparently I should concat the substraction to the date like the following:
const diff = "-5"
const utcDate = "2017-02-22 17:28:13"
const date = new Date(utcDate + diff[0] + ' ' + diff[1])
//desired output: 2017-02-22 12:28:13
But I can't seem to make it work.
I do all my Date calculations with .getTime().
So an hour is 3600000 milliseconds.
const MILLISECONDS_HOUR = 3600000;
const diff = -5;
const utcDate_str = "2017-02-22 17:28:13";
const utcDate = new Date( utcDate_str );
const minus_5_hours = new Date( utcDate.getTime() + ( MILLISECONDS_HOUR * diff ));
console.log( utcDate.toJSON());
console.log( minus_5_hours.toJSON());
The big advantage is that javascript will take care of leap years, month boundaries and such.
But since you are calling your variable diff, are you trying to calculate lcoal time vs UTC time?
In that case, reread the javascript Date methods. There's a bunch of methods to handle both UTC and local time, for example: date.getUTCDate() and date.getDate().
So you might not have to calculate all of this yourself.
Also, if you format your dates according to the ISO, "2017-02-22T17:28:13.000Z", this will automatically get parsed as UTC.
someDate.setHours(someDate.getHours()+1);
From https://stackoverflow.com/a/1050782/537998
I have a form and one button to plus some minutes to a time(hh:MM), but the time is a span tag.
At Firefox works well, but when I tested at Chrome doesn't work the Date(). What happened?
//Botão adicionar horário agenda.
$('.button').click(function() {
var $duration_schedule = $('#duration');
var duration = $duration_schedule.val(); // 30
var hour = $('.time_schedule_form').text(); // 10:00
var new_time = self.Plus_minutes(hour, duration);
alert(new_time); // 10:30
});
Plus_minutes: function(hour, duration) {
var time, new_hour, hours = '';
time = new Date("T"+hour); // Erro at Chrome
time.setTime(time.getTime() + duration*60000);
hours = time.getHours().toString();
minutes = time.getMinutes().toString();
if (minutes.length > 1) {
new_hour = hours + ':' + minutes;
} else {
new_hour = hours + ':0' + minutes;
}
return new_hour;
},
I suppose that it is happening because of constructor's input! In case of time you should put numbers in milliseconds. The Data Object have those constructors bellow:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month[, date[, hours[, minutes[, seconds[,milliseconds]]]]]);
you can take at look at Developer.mozilla then you can check a better explanation about formats.
Maybe the Firefox are converting to including something in that part of code. I found out other explanation about Data input formats, you can take a look too at: Convert String to Date
The correct format for UTC would be like 2013-02-27T17:00:00Z (Z is for Zulu Time). Append Z if not present to get correct UTC datetime string.
You could achieve this using setMinutes to update using getMinutes.
newdate.setMinutes(newdate.getMinutes() + 10);
I am using momentjs but having an issue trying to convert a UTC time to a specific timezone (not necessarily local to the current user) that is specified by name 'America/New_York'. This SO question is similar but didn't really help.
My thought process is to create a utc moment obj with the received date from the server and then format that UTC time to the specific timezone for display purposes. A small snippet of how I'm currently approaching this:
var cutoffString = '20170421 16:30:00'; // in utc
var utcCutoff = moment.tz(cutoffString, 'YYYYMMDD HH:mm:ss', '+00:00');
var displayCutoff =
moment.tz(utcCutoff.format('YYYYMMDD HH:mm:ss'), 'YYYYMMDD HH:mm:ss', 'America/New_York');
console.log('utcCutoff:', utcCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => utcCutoff: 20170421 04:30:00pm +00:00
console.log('displayCutoff:', displayCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => displayCutoff: 20170421 04:30:00pm +00:00
My assumption here is that displayCutoff would be the utcCutoff time displayed in 'America/New_York' time. But it currently is displays the same time as the utcCutoff object. I also should mention that using .utc() instead of .tz and trying to manipulate the timezone after applying .local() did not work either.
Any help/guidance would be appreciated.
You can use moment.utc since your input is an UTC string. You can use tz to convert your moment object to a given timezone.
Please note that the tz function converts moment object to a given zone, while you are using moment.tz parsing function that builds a new moment object with the given zone. When you do:
var displayCutoff =
moment.tz(utcCutoff.format('YYYYMMDD HH:mm:ss'), 'YYYYMMDD HH:mm:ss', 'America/New_York');
you are not converting utcCutoff to 'America/New_York' but you are building a new moment object for 20170421 16:30:00 in New York.
Here an updated version of your code:
var cutoffString = '20170421 16:30:00'; // in utc
var utcCutoff = moment.utc(cutoffString, 'YYYYMMDD HH:mm:ss');
var displayCutoff = utcCutoff.clone().tz('America/New_York');
console.log('utcCutoff:', utcCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => utcCutoff: 20170421 04:30:00pm +00:00
console.log('displayCutoff:', displayCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => displayCutoff: 20170421 12:30:00pm -04:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone-with-data-2010-2020.min.js"></script>
Moment timezone plugin is exactly what you need : http://momentjs.com/timezone/
var dec = moment("2014-12-01T12:00:00Z");
dec.tz('America/New_York').format('ha z'); // 5am PDT
With momentjs-timezone you can convert from any timezone to any other timezone.
You need to specify the start time zone and before formatting the target timezone.
Here is an example which converts a date time from UTC to three other timezones:
const moment = require('moment-timezone')
const start = moment.tz("2021-12-08T10:00:00", "UTC") // original timezone
console.log(start.tz("America/Los_Angeles").format())
console.log(start.tz("Asia/Calcutta").format())
console.log(start.tz("Canada/Eastern").format())
This will print out:
2021-12-08T02:00:00-08:00
2021-12-08T15:30:00+05:30
2021-12-08T05:00:00-05:00
Instead of UTC as start timezone you can use any other timezone too, like "Asia/Seoul" and obviously get different results with the same script:
const moment = require('moment-timezone')
const start = moment.tz("2021-12-08T10:00:00", "Asia/Seoul")
console.log(start.tz("America/Los_Angeles").format())
console.log(start.tz("Asia/Calcutta").format())
console.log(start.tz("Canada/Eastern").format())
This prints out:
2021-12-07T17:00:00-08:00
2021-12-08T06:30:00+05:30
2021-12-07T20:00:00-05:00
All momentjs timezones are listed here:
https://gist.github.com/diogocapela/12c6617fc87607d11fd62d2a4f42b02a
There is no need to use MomentJs to convert your timezone to specific timezone. Just follow my given below code, it will work for you :
$(document).ready(function() {
//EST
setInterval( function() {
var estTime = new Date();
var currentDateTimeCentralTimeZone = new Date(estTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
var seconds = currentDateTimeCentralTimeZone.getSeconds();
var minutes = currentDateTimeCentralTimeZone.getMinutes();
var hours = currentDateTimeCentralTimeZone.getHours();//new Date().getHours();
var am_pm = currentDateTimeCentralTimeZone.getHours() >= 12 ? "PM" : "AM";
if (hours < 10){
hours = "0" + hours;
}
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
var mid='PM';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='AM';
}
var x3 = hours+':'+minutes+':'+seconds +' '+am_pm
// Add a leading zero to seconds value
$("#sec").html(x3);
},1000);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p class="date_time"><strong id="sec"></strong> </p>
</body>
</html>
I'm receiving date and time from the REST API in the below format
2016-01-17T:08:44:29+0100
I want to format this date and time stamp like
17-01-2016 08:44:29
It should be dd/mm/yyyy hh:mm:ss
How to format this in TypeScript?
you can use moment.js. install moment js in your project
moment("2016-01-17T:08:44:29+0100").format('MM/DD/YYYY');
for more format option check Moment.format()
Have a look at this answer
You can create a new Date("2016-01-17T08:44:29+0100") //removed a colon object and then get the month, day, year, hours, minutes, and seconds by extracting them from the Date object, and then create your string. See snippet:
const date = new Date("2016-01-17T08:44:29+0100"); // had to remove the colon (:) after the T in order to make it work
const day = date.getDate();
const monthIndex = date.getMonth();
const year = date.getFullYear();
const minutes = date.getMinutes();
const hours = date.getHours();
const seconds = date.getSeconds();
const myFormattedDate = day+"-"+(monthIndex+1)+"-"+year+" "+ hours+":"+minutes+":"+seconds;
document.getElementById("dateExample").innerHTML = myFormattedDate
<p id="dateExample"></p>
It is not the most elegant way, but it works.
Check if this is helpful.
var reTime = /(\d+\-\d+\-\d+)\D\:(\d+\:\d+\:\d+).+/;
var originalTime = '2016-01-17T:08:44:29+0100';
var newTime = originalTime.replace(this.reTime, '$1 $2');
console.log('newTime:', newTime);
Output:
newTime: 2016-01-17 08:44:29
new Date().toLocaleString()
output:
"31/03/2020 ,00:00:0"
(now,your output is string)
How can I convert seconds to HH:mm:ss?
At the moment I am using the function below
render: function (data){
return new Date(data*1000).toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");;
}
This works on chrome but in firefox for 12 seconds I get 01:00:12
I would like to use moment.js for cross browser compatibility
I tried this but does not work
render: function (data){
return moment(data).format('HH:mm:ss');
}
What am I doing wrong?
EDIT
I managed to find a solution without moment.js which is as follow
return (new Date(data * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
Still curious on how I can do it in moment.js
This is similar to the answer mplungjan referenced from another post, but more concise:
const secs = 456;
const formatted = moment.utc(secs*1000).format('HH:mm:ss');
document.write(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.
From this post I would try this to avoid leap issues
moment("2015-01-01").startOf('day')
.seconds(s)
.format('H:mm:ss');
I did not run jsPerf, but I would think this is faster than creating new date objects a million times
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
function pad(num) {
return ("0"+num).slice(-2);
}
function hhmmss(secs) {
var minutes = Math.floor(secs / 60);
secs = secs%60;
var hours = Math.floor(minutes/60)
minutes = minutes%60;
return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
// return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}
for (var i=60;i<=60*60*5;i++) {
document.write(hhmmss(i)+'<br/>');
}
/*
function show(s) {
var d = new Date();
var d1 = new Date(d.getTime()+s*1000);
var hms = hhmmss(s);
return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);
}
*/
You can use moment-duration-format plugin:
var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
See also this Fiddle
Upd: To avoid trimming for values less than 60-sec use { trim: false }:
var formatted = duration.format("hh:mm:ss", { trim: false }); // "00:00:05"
var seconds = 2000 ; // or "2000"
seconds = parseInt(seconds) //because moment js dont know to handle number in string format
var format = Math.floor(moment.duration(seconds,'seconds').asHours()) + ':' + moment.duration(seconds,'seconds').minutes() + ':' + moment.duration(seconds,'seconds').seconds();
My solution for changing seconds (number) to string format (for example: 'mm:ss'):
const formattedSeconds = moment().startOf('day').seconds(S).format('mm:ss');
Write your seconds instead 'S' in example.
And just use the 'formattedSeconds' where you need.
In a better way to utiliza moments.js; you can convert the number of seconds to human-readable words like ( a few seconds, 2 minutes, an hour).
Example below should convert 30 seconds to "a few seconds"
moment.duration({"seconds": 30}).humanize()
Other useful features: "minutes", "hours"
The above examples may work for someone but none did for me, so I figure out a much simpler approach
var formatted = moment.utc(seconds*1000).format("mm:ss");
console.log(formatted);
Until 24 hrs.
As Duration.format is deprecated, with moment#2.23.0
const seconds = 123;
moment.utc(moment.duration(seconds,'seconds').as('milliseconds')).format('HH:mm:ss');
How to correctly use moment.js durations?
|
Use moment.duration() in codes
First, you need to import moment and moment-duration-format.
import moment from 'moment';
import 'moment-duration-format';
Then, use duration function. Let us apply the above example: 28800 = 8 am.
moment.duration(28800, "seconds").format("h:mm a");
🎉Well, you do not have above type error. 🤔Do you get a right value 8:00 am ? No…, the value you get is 8:00 a. Moment.js format is not working as it is supposed to.
💡The solution is to transform seconds to milliseconds and use UTC time.
moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a')
All right we get 8:00 am now. If you want 8 am instead of 8:00 am for integral time, we need to do RegExp
const time = moment.utc(moment.duration(value, 'seconds').asMilliseconds()).format('h:mm a');
time.replace(/:00/g, '')
To display number of days along with hours, mins and seconds, you can do something like this:
const totalSec = 126102;
const remainingMillies= (totalSec % 86400) * 1000;
const formatted = `${Math.floor(totalSec / 86400)} day(s) and ${moment.utc(remainingMillies).format('hh:mm:ss')}`;
console.log(formatted );
will output :
1 day(s) and 11:01:42
In 2022 no need for any new plugin just do this
Literally all you need in 2022 prints out duration in hh:mm:ss from two different date strings
<Moment format='hh:mm:ss' duration={startTime} date={endTime} />
I think there's no need to use 3rd part libray/pluggin to get this task done
when using momentJS version 2.29.4 :
private getFormatedDuration(start: Date, end: Date): string {
// parse 'normal' Date values to momentJS values
const startDate = moment(start);
const endDate = moment(end);
// calculate and convert to momentJS duration
const duration = moment.duration(endDate.diff(startDate));
// retrieve wanted values from duration
const hours = duration.asHours().toString().split('.')[0];
const minutes = duration.minutes();
// voilà ! without using any 3rd library ..
return `${hours} h ${minutes} min`;
}
supports also 24h format
PS : you can test and calculate by yourself using a 'decimal to time' calculator at CalculatorSoup