I have a function that will create two dates using the result of an input with Bootstrap DateTime Picker and I need to compare both of them.
But my first value (rtime) always gives an invalid date. Where am I wrong?
Note: stime is not editable, the user only uses the DateTime Picker for rtime field.
var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';
var lastReturn = new Date(rtime);
var lastOut = new Date(stime);
if (lastReturn >= lastOut) {
console.log("This date is after than the other!");
}
console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);
This result shows that LastOut is an invalid date:
The format must be month/day/year, not day/month/year
That why you get invallid date on 28/11/2017 09:18:52 because there isn't a 28th month.
console.log(new Date('28/11/2017 09:18:52'))
console.log(new Date('11/28/2017 09:18:52'))
The dates you're picking are probably Month/Day/Year. But your expected date is Day/Month/Year. For example, the date 04/12/2017 is returning April 12th instead of December 4th. You can use a regex on your string to replace and make it in the correct format.
Please check this snippet:
var stime = "28/11/2017 09:18:52" //$("#movesend").val();
var rtime = "04/12/2017 10:16:34" //$("#moveretorna").val();
function parseDate(dateString) {
return dateString.replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
}
var lastReturn= new Date(parseDate(rtime));
var lastOut= new Date(parseDate(stime));
if(lastReturn>= lastOut)
{
console.log("This date is after than the other!");
}
console.log(stime);
console.log(rtime);
console.log(lastReturn);
console.log(lastOut);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to convert your date from DD/MM/YYYY HH:MM:SS format to MM/DD/YYYY HH:MM:SS format.
For conversion, you can use string#replace.
var stime = '28/11/2017 09:18:52';
var rtime = '04/12/2017 10:16:34';
stime = stime.replace(/(..)\/(..)\/(.*)/, '$2/$1/$3');
rtime = rtime.replace(/(..)\/(..)\/(.*)/, '$2/$1/$3');
var lastReturn = new Date(rtime);
var lastOut = new Date(stime);
if (lastReturn >= lastOut) {
console.log("This date is after than the other!");
}
console.log(rtime);
console.log(stime);
console.log(lastReturn);
console.log(lastOut);
Related
I am having a date string '2021-09-27 07:43' I also have the info that the date is in (GMT-8:00) Alaska time zone. I am in a different local timezone. When i convert this date to UTC , it is taking my timezone as the reference timezone.
const str = new Date().toLocaleString('en-US', { timeZone: 'Etc/GMT' });
How to do it with respect to a specific time zone as the reference rather than my local time?
You can convert it using moment.js.
see Example:
var input = '2021-09-27 07:43';
var fmt = 'YYYY-MM-DD HH:mm'; // must match the input
var zone = 'Etc/GMT';
var m = moment.tz(input, fmt, zone);
m.utc();
var s = m.format(fmt) // result:
console.log(s);
<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>
Try:
let myDate = "2021-09-27 07:43";
let myDateUTC = new Date(myDate + " UTC-8"); // 2021-09-27T15:43:00.000Z
How to convert a date(01-02-2019) to Wed, 02 Jan 2019 in javascript?
$(document).ready(function () {
var dealDate = 01-02-2019;
});
Just use new Date() on that date value:
$(document).ready(function() {
var dealDate = '01-02-2019';
//replace all - to / to make it work on firefox
dealDate = dealDate.replace(/-/g,'/');
alert(new Date(dealDate).toDateString())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use Date Constructor and Date.prototype.toDateString():
The toDateString() method returns the date portion of a Date object in human readable form in American English.
$(document).ready(function () {
var dealDate = new Date('01-02-2019').toDateString();
console.log(dealDate);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can split your string on - and then generate the date using Date constructor.
var dealDate = '01-02-2019';
let [month, day, year] = dealDate.split('-').map(Number);
let date = new Date(year, month - 1, day);
console.log(date.toDateString());
TO convert the date to in the format of month day, month day number and year use the below jquery. It will convert the current date to the exact format you asked for
$(document).ready(function() {
var dealDate = new Date();
alert(dealDate.toUTCString());
});
your expected format is like [day][comma][date][month][year]. I split toDateString() and rearranged in expected format.
function formatedDate(d){
var dt=new Date(d).toDateString().split(' ');
return dt[0]+', '+dt[2]+' '+dt[1]+' '+dt[3]; //[Day][comma][date][month][year]
}
console.log(formatedDate('01-02-2019'))
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 want to parse date in the format ddMMyyhhmm (eg 2804121530 representing 28th April 2012, 3:30 PM) to javascript Date() object.
Is there any oneliner solution to it? I'm looking for something of the kind:
var date = Date.parse('2804121530', 'ddMMyyhhmm');
or
var date = new Date('2804121530', 'ddMMyyhhmm');
Thanks for help!
A useful library here is DateJs. Just add a reference:
<script src="http://datejs.googlecode.com/files/date.js"
type="text/javascript"></script>
and use Date.parseExact:
var dateStr = '2804121530';
var date = Date.parseExact(dateStr, 'ddMMyyHHmm');
For a fast solution you can brake that string into pieces and create date from those pieces
function myDateFormat(myDate){
var day = myDate[0]+''+myDate[1];
var month = parseInt(myDate[2]+''+myDate[3], 10) - 1;
var year = '20'+myDate[4]+''+myDate[5];
var hour = myDate[6]+''+myDate[7];
var minute = myDate[8]+''+myDate[9];
return new Date(year,month,day,hour,minute,0,0);
}
var myDate = myDateFormat('2804121530');
or a simper solution:
function myDateFormat(myDate){
return new Date(('20'+myDate.slice(4,6)),(parseInt(myDate.slice(2,4), 10)-1),myDate.slice(0,2),myDate.slice(6,8),myDate.slice(8,10),0,0);
}
var myDate = myDateFormat('2804121530');
(new Date(1381344723000)).toUTCString()
Correct me if 'm worng...