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)
Related
I have date and time format in this form:
1628489237000
I want in the below format:
DD/MM/YYYY and time.
I want to use that in javascript.
Just like this for date:
new Date(1628489237000).toLocaleDateString()
or for time:
new Date(1628489237000).toLocaleTimeString()
If you can use library, I would like to recommend you dayjs
with dayjs,
dayjs().format('DD/MM/YYYY') // 10/08/2021'
var timestamp = 1607110465663;
var date = new Date(timestamp);
var month=''+date.getMonth();
var day=''+date.getDate();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
console.log("Date: "+day+
"/"+month+
"/"+date.getFullYear()+
" "+date.getHours()+
":"+date.getMinutes()+
":"+date.getSeconds());
if yout want to time to hh/mm/ss you can convert with condition "length"
There is also a solution that uses momentjs library:
console.log(moment(1628489237000).format('DD/MM/YYYY'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
DateTime.Now.ToString("MM/dd/yyyy")
No need for any library for your case, especially not moment.js. You can read more about the project status here
var timestamp = 1628489237000;
// Create date from timestamp
var date = new Date(timestamp);
// Format date
var formattedDate = date.toLocaleDateString('fr');
var formattedTime = date.toLocaleTimeString('fr');
// Print results
console.log(formattedDate); // "09/08/2021"
console.log(formattedTime); // "8:07:17 AM"
console.log(`${formattedDate} ${formattedTime}`); // "09/08/2021 8:07:17 AM"
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 2 DateTime field in a form, and I want the difference between these 2 fields in minute.
I tried to parse DateTime into Date but it's not working :
<script>
$(document).ready(function () {
$("#mybundle_evenement_button").click(function () {
var field1 = $("#mybundle_evenement_debut").val();
var field2 = $("#mybundle_evenement_fin").val();
var date1 = new Date(field1);
var date2 = new Date(field2);
alert(date1);
});
});
</script>
If I alert() date1, it shows Invalid Date.
But if I alert() field1, it shows 15/09/2017 13:32 (format is : days/months/year hour:minutes).
Is it possible that new Date(field1) isn't working because of the format ?
I know that if I succeed to parse DateTime into Date, it'll be easy to have the difference in minutes, but I don't understand why it says Invalid Date.
dd/MM/yyyy HH:mm isn't a valid date format for Date.parse()
You have to format your date to a valid Date Time String Format, for example:
var field1 = $("#mybundle_evenement_debut").val();
var ISODate1 = field1.replace(/(\d+)\/(\d+)\/(\d+)/, "$3-$2-$1")
var date1 = new Date(ISODate1);
alert(date1) // => Fri Sep 15 2017 13:32:00 ...
The problem is about the format you are getting the date from the field. new Date() don't accepts this format. I think the best is to parse the string yourself. If the format is always the same just use new Date(year, month, day, hours, minutes, seconds, milliseconds).
var day = field.splice(0,2); field.splice(0,1);
var month = field.splice(0,2); field.splice(0,1);
var year = field.splice(0,2); field.splice(0,1);
var hour = field.splice(0,2); field.splice(0,1);
var minute = field.splice(0,2);
It's depend on your browser. I'll suggest to use the standard format is '2013/12/09 10:00'.
Okay! come to the point. You need to manually format the date from my latest answer regarding this same kind of issue. Please take a look at this link : Stange javascript Date behaviour on particular dates
And you could try this below code for getting the date difference in minutes.
var startTime = new Date('2013/12/09 10:00');
var endTime = new Date('2014/12/09 10:00');
var difference = endTime.getTime() - startTime.getTime();
var result = Math.round(difference / 60000);
alert(result);
I'm trying to convert UTC time to the local time. I've been following this example from this link: http://jsfiddle.net/FLhpq/4/light/. I can't seem to get the right local output. For example, if its 10: 30 am in here, instead of getting 10:30 ill get 15: 30. Here is my code:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
var localTime = moment.utc(date).toDate();
localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
console.log("moment: " + localTime);
No matter what I do the time always comes out at UTC time. I live in Houston so I know timezone is the issue. I've followed the code in the link but can seem to get the local time. What am I doing wrong?
To convert UTC time to Local you have to use moment.local().
For more info see docs
Example:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // 2015-09-13 03:39:27
var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');
console.log(local); // 2015-09-13 09:39:27
Demo:
var date = moment.utc().format();
console.log(date, "- now in UTC");
var local = moment.utc(date).local().format();
console.log(local, "- UTC now to local");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Try this:
let utcTime = "2017-02-02 08:00:13";
var local_date= moment.utc(utcTime).local().format('YYYY-MM-DD HH:mm:ss');
let utcTime = "2017-02-02 08:00:13.567";
var offset = moment().utcOffset();
var localText = moment.utc(utcTime).utcOffset(offset).format("L LT");
Try this JsFiddle
To convert UTC to local time
let UTC = moment.utc()
let local = moment(UTC).local()
Or you want directly get the local time
let local = moment()
var UTC = moment.utc()
console.log(UTC.format()); // UTC time
var cLocal = UTC.local()
console.log(cLocal.format()); // Convert UTC time
var local = moment();
console.log(local.format()); // Local time
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Note: please update the date format accordingly.
Format Date
__formatDate: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('D-MMM-Y');
}
Format Time
__formatTime: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('HH:mm');
},
This is old question I see, but I didn't really get what I was looking for. I had a UTC datetime which was formatted without timezone. So I had to do this:
let utcDatetime = '2021-05-31 10:20:00';
let localDatetime = moment(utcDatetime + '+00:00').local().format('YYYY-MM-DD HH:mm:ss');
I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!
Full Example on Codesandbox (DEMO):
https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js
This is what worked for me, it required moment-tz as well as moment though.
const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()
Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');
I've created one function which converts all the timezones into local time.
Requirements:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"
I have the following code which I get from parameters in the URL.
This is what I have in the URL
&dateStart=15.01.2015&timeStart=08%3A00&
After getting the parameters I have the following: 15.01.2015:08:00
Using Javascript how can I parse this string to get the date in milliseconds?
Date.parse(15.01.2015:08:00)
But obviously this doesn't work.
Date.parse(15-01-2015)
This works and I can change this but then how do I add or get the milliseconds from the time??
This is quite possibly the ugliest JavaScript function I've written in my life but it should work for you.
function millisecondsFromMyDateTime(dateTime) {
var dayMonth = dateTime.split('.');
var yearHourMinute = dayMonth[2].split(':');
var year = yearHourMinute[0];
var month = parseInt(dayMonth[1]) - 1;
var day = dayMonth[0];
var hour = yearHourMinute[1];
var minute = yearHourMinute[2];
var dateTimeObj = new Date(year, month, day, hour, minute, 0, 0);
return dateTimeObj.getTime();
}
It will work with the format that your DateTime is in aka day.month.year:hours:minutes.
You can achieve it using Javascript Date Object and JavaScript getTime() Method:
var dateString="01.15.2015 08:00";
var d = new Date(dateString);
console.log(d);
var ms=d.getTime();
console.log(ms);
ms+=10000;
console.log(new Date(ms));
Here is a DEMO Fiddle.
Note: Change your date string from 15.01.2015:08:00 to "01.15.2015 08:00" because it's not a valid Date format.
Check for format
Date() in javascript :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Format allowed :
https://www.rfc-editor.org/rfc/rfc2822#page-14
You can try to use moment.js library like this:
moment('15.01.2015 08:00', 'DD.MM.YYYY HH:mm').milliseconds()
Just for the sake of completion, you can always extract the information and create a Date object from the extracted data.
var dateStart = '15.01.2015'
var timeStart = '08:00';
var year = dateStart.substring(6,10);
var month = dateStart.substring(3,5);
var day = dateStart.substring(0,2);
var hour = timeStart.substring(0,2);
var mins = timeStart.substring(3,5);
var fulldate = new Date(year, month-1, day, hour, mins);
console.log(fulldate.getTime());