moment js change the date portion of a datetime - javascript

Using the moment.js library say i have a datetime with today's date and i would like to replace only the date part of the datetime with another value and keep the time portion the same
I don't want to subtract or add days etc - i have a 3rd party time picker that when you select a time it creates a datetime that is always the current day. I need to send back to server a different datetime - the date is different but keep the time portion from the picker.
example code:
let myDate = "2019-03-15T00:00:00"
let selectedDateTime = "2019-04-04T12:30:00"
expected result would be:
"2019-03-15T12:30:00"
Thank you

The following should solve your problem:
let myDate = moment("2019-03-15T00:00:00")
let selectedDateTime = moment("2019-04-04T12:30:00")
selectedDateTime.date(myDate.date());
selectedDateTime.month(myDate.month());
selectedDateTime.year(myDate.year());
As #JeremyThille suggested, you should take a look at the documentation.

Related

How to format timestamp to a calendar format date?

I'm using devExtreme dxScheduler and i'm trying to display meetings after fetching them from api, the problem is that i can't recreate the original date format ("YYYY-MM-DDThh:mm:ssZ") since i'm getting the dates as timestamp.
Here is how it's stores :
var startDate = moment("2021-05-24T16:30:00.000Z").valueOf()
// 1621873800000
Here is what i'm trying to do to recreate the format:
var startDate = moment(new Date(startDate)).format("YYYY-MM-DDThh:mm:ssZ")
//"2021-05-24T07:30:00+03:00"
Notice that the original date ("2021-05-24T16:30:00.000Z") and the formatted date ("2021-05-24T07:30:00+03:00") are different ...hence the calendar do not displays them.
Looks like the date is being converted into your local timezone, thus the difference. You may need to add Moment Timezone to be able to get the timezone back in to recreate it to the format you need. Also consider adding utc() before the format to bring it to Zulu time.
Fix 1
I see from the DevExtreme page that it needs to be displayed within this format:
currentDate: new Date(2021, 4, 27)
Maybe you need to format it before adding it like this:
var check = moment("2021-05-24T16:30:00.000Z", 'YYYY/MM/DD');
var month = check.format('M');
var day = check.format('D');
var year = check.format('YYYY');
console.log(month,day,year);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
And then in your dxScheduler add the property like this:
currentDate: new Date(year, month, day);
Fix 2
If that's not the problem, you can install moment-timezone
var a = moment.utc("2013-11-18 11:55").tz("Asia/Taipei");
var b = moment.utc("2013-11-18 11:55").tz("America/Toronto");
a.format(); // 2013-11-18T19:55:00+08:00
b.format(); // 2013-11-18T06:55:00-05:00
a.utc().format(); // 2013-11-18T11:55Z
b.utc().format(); // 2013-11-18T11:55Z
In this example, you first create moment.utc("2013-11-18 11:55") object in UTC, and then change its timezone to specified. This also works if you create the object in your default timezone: moment("2013-11-18 11:55").
Note that created moments have equal UTC time because these moments were created in a default timezone.
Turns out that displaying a calendar event with DevExtreme requires only to use regular date object.... so no need to do anything spacial.

Convert hour to date time without adding +1

Hi im using moment js to convert this string 20:00 I tried:
var a = moment("20:00", "HH:mm")
console.log(a.format()) // 2016-09-08T20:00:00+01:00
the problem when I store in mongodb it become
2016-09-10T19:00:00.000Z
I want to store 2016-09-10T20:00:00.000Z
anyway can explain why please ?
When you say that you want to store 2016-09-10T20:00:00.000Z what you are saying is that you want to assume that your date and time is UTC.
To assume that the date you are parsing is a UTC value, use moment.utc
var a = moment.utc("20:00", "HH:mm")
console.log(a.format()) // 2016-09-08T20:00:00Z
Note that when you parse a time without a date, moment assumes the current date. This may not be the behavior that you want.
I'm also not sure if you want a UTC date (which is what you are saying), or a local date without an offset indicator. If you want a local date without an offset indicator, simply use a format without an offset:
moment.utc("20:00", "HH:mm").format('YYYY-MM-DDTHH:mm:ss.SSS')
"2016-09-08T20:00:00.000"
If you are dealing with local dates that do not have a time zone association, I recommend using moment.utc to parse, as this will ensure that the time does not get shifted to account for DST in the current time zone.
For more information about how to parse dates into the time zone or offset that you would like in moment, see my blog post on the subject.
This it how it should look:
var a = moment("20:00", "HH:mm")
console.log(a.utcOffset('+0000').format())
<script src="http://momentjs.com/downloads/moment.min.js"></script>
Doe, the problem is that you are using timezones when you create the date.
MomentJS uses your current timezone automatically.
Mongo however saves the time as it would be in another timezone.
Therefore, if you want the two strings to format the same way, you need to set the timezone.

Bootstrap datetime picker picking day before selected

I am using this bootstrap datetime picker. I noticed that when I choose a day and convert the milliseconds using var d1 = new Date(milliseconds); it is converted into the day before my selected day. Is there a particular reason for this?
Example:
I select Tuesday, October 1st:
I log the date object after it is converted:
You must convert it into a Unix timestamp , which is a better way of tracking date/time.
Use new Date('your_date_string').getTime() / 1000 which gives you the timestamp or using PHP (strtotime) .
The date object that is being logged for you is probably coming from your system/browser settings(local).
Do not use JavaScript date and time calculations in web applications unless you ABSOLUTELY have to.
While you have the timestamp, cross-check if you are getting the correct time.

Java Script: How to ammend a datetime variable to set a specific time?

I need to take a datetime values from an MSSQL based app which is read into the script as 22/12/2010 3:56pm and adjsut the time component toa set time.
I've used what I know of javascript and what I can find in google searches to try and progress this but to no avail.
Premis: I need to read the date time value and set the time portion of the date to 8am, 1pm or 4pm dependent on another field.
The conditional logic portion of the script is fine the date functions aren't so fine.
Current code I'm currently using:
if(fldPriority.Value=='2')
{
var ResDate = new Date(fldTargetResolutionTime.Value);
var newdate = new Date(ResDate.getYear(),ResDate.GetMonth(),ResDate.GetDay(),16,0,0,0);
objReturn = newdate
}
Problem:
The date reads in originally in gmt format 22/12/2010 3:56pm but then gets changes to utc format and the date changes significantly to Wed Oct 12 15:56:00 UTC+12 2011
Any help would be greatly appreciated.
Make a copy of the Date and set the time using UTCHours.
The return value will be the correct Date and time,
but you if need to convert it to a string the string will be local time unless you call newDate.toUTCString();
(or objReturn.toUTCString())
var newdate=new Date(ResDate);
newDate.setUTCHours(16,0,0,0);
objReturn=newDate;

How to get difference of saved time and current time in jquery?

I want to get the time difference between saved time and current time in javascript or jquery. My saved time looks like Sun Oct 24 15:55:56 GMT+05:30 2010.
The date format code in java looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
How to compare it with the current time and get the difference?
Is there any inbuilt function in jquery or javascript??
Any suggestions or links would be appreciative!!!
Thanks in Advance!
Update
Date is stored as varchar in the DB. I am retriving it to a String variable and then change it to java.util.Date object. The java code looks like
String newDate = "2010/10/24 15:55:56";
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = format.parse(newDate);
This date object was sent to client. There i want to compare the saved date with current date and want to show the time difference like 2 secs ago, 2 hours ago, 2 days ago etc... like exactly in facebook. I have gone through some date to timestamp conversion tutorial in java script and now i can get the difference in timestamp. Now, i want to know how i shall change it to some format like "2 secs or 2 days or 24 hours"??. Or, how i shall change it back to date format???
Convert them into timestamps which are actually integers and can get subtracted from each other. The you just have to convert back the resulting timestamp to a javascript date object.
var diff = new Date();
diff.setTime( time2.getTime()-time1.getTime() );
You dont need to explicit convert, just do this:
var timediff = new Date() - savedTime;
This will return the difference in milliseconds.
jQuery doesn't add anything for working with dates. I'd recommend using Datejs in the event that the standard JavaScript Date API isn't sufficient.
Perhaps you could clarify exactly what input and output you're aiming for. What do you mean by "the difference?" There is more than one way to express the difference between to instants in time (primarily units and output string formatting).
Edit: since you said you're working with jQuery, how about using CuteTime? (Demo page)

Categories

Resources