Retaining the last modified date while using ChannelSftp for file transfer - jsch

I am using ChannelSftp(jsch-0.1.42.jar) to copy files from a unix server and can successfully do it but the last modified date gets overwritten by the current time.
I am using
chanSftp.get(nextName, "C:/Test/" + nextName);
Is there any way of retaining the last modified time of the remote file on the local copy?
I have the last modified time of the remote file which i got using
attrs = lsEntry.getAttrs();
Date modDate = (Date) format.parse(attrs.getMtimeString());

Using a SimpleDateFormat is of less performance. Instead one could use the methods getMTime() and getATime() directly. But they deliver a value reduced by the milliseconds.
That's why they return an int and not a long as expected in conformance to date.getTime().
SftpATTRS attrs = lsEntry.getAttrs();
Date dateModify = new Date(attrs.getMTime() * 1000L);
Date dateAccess = new Date(attrs.getATime() * 1000L);
In jsch-0.1.50 be careful of using getAtimeString() there is the factor 1000L missing.
In jsch-0.1.51 the getAtimeString() bug with the missing factor is fixed.

This changes the last modified time of the file downloaded from the remote server,
String remoteFilePath = "testDir/testFile.txt";
SftpATTRS attrs = sftpChannel.lstat(remoteFilePath);
SimpleDateFormat format = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
Date modDate = (Date) format.parse(attrs.getMtimeString());
String localFilePath = "C:/temp/downloadedFile.txt";
sftpChannel.get(remoteFilePath, localFilePath);
File downloadedFile = new File(localFilePath);
downloadedFile.setLastModified(modDate.getTime());

Merging the answers above to a working solution:
sftpChannel.get(REMOTE_FILE, LOCAL_FILE);
SftpATTRS attrs = sftpChannel.lstat(REMOTE_FILE);
Date dateModify = new Date(attrs.getMTime() * 1000L);
File downloadedFile = new File(LOCAL_FILE);
downloadedFile.setLastModified(dateModify.getTime())

Related

Cucumber-java-Startdate shouldn't be todays date in Java script

I am new to this code.
While running automation script, the date is automatically picked todays date.
actually the date starts from 01/01/2022.
How to change this code?
public void validateStartDateDefaultValueNew() throws Exception{
Date date = Calendar.getInstance().getTime();
DateFormat date formatter = new SimpleDateFormat( pattern: "dd/MM/yyyy");
String today = dateformatter.format(date);
System.out.println("today is "+today);
System.out.println("formatted today is "+date formatter.parse(today))
String [] actual1 = searchStartDateInput.getAttribute("value").split(regor " ");
String actual actuall[0]; =
System.out.println("today actual app is [+actual);
Assert.assertEquals(today, actual);
In your code, you mentioned -
'Date date = Calendar.getInstance().getTime();'.
This line of code takes today's date and current time.
If you want the start date to be '01/01/2022', then hard-code it in your code.

How do I return the local time portion of a string given a date string

I am wanting to display in a react native app a date given by the API.
The API is returning the following value:
"2022-06-20T14:00:00.000"
I need to display to the user
2:00 PM
The problem is that when I try this:
const dateString = "2022-06-20T14:00:00.000"
const date = new Date(dateString);
console.log(date)
The date has been changed to:
2022-06-20T14:00:00.000Z
Meaning it is 2pm UTC time when it should be 2pm local time.
On the end of the new Date variable, if you add the .toLocaleTimeString(), it should then output as 2:00:00PM.
const date = new Date(dateString).toLocaleTimeString();
you can use moment library with its localized formats,
here is the documentation for more of its formats https://momentjscom.readthedocs.io/en/latest/moment/04-displaying/01-format/
const dateString = "2022-06-20T14:00:00.000"
console.log(moment(dateString).format('LT'))

Nest Js Typeorm Query

I am trying to run a query at the repository level of my nestjs application.
The date format of the column (runDateTime) in my DB is isoString. I want to find all the records that have runDateTime of today's date.
I have a function called Parsebackenddate that essentially converts iso string to YYYY-MM-DD. how do i use this function with "schedule.runDateTime" in order to compare both dates in the format YYYY-MM-DD?
Or is there an alternative?
if (getToday) {
const todayDate = dayjs().format('YYYY-MM-DD');
query.where('schedule.runDateTime = :todayDate', {
todayDate,
});
``
Much appreciated.
first, you have to get a date from the database and hold it in a class variable then compare.
something like that may this could help.
var _orderBean = new date_beans();
_orderBean.dueDate = _response[a].dueDate.toISOString().slice(0,10); //YYYY-MM-DD
then compare
var d = new Date(); //todaydate
if(d.toISOString().slice(0,10)>_orderBean.dueDate)
// TodayDate > DueDate

Kotlin SimpleDateFormat parse wrong timezone

My mobile timezone was GMT+7, I have a code to convert a specific date time(GMT+0) to a specific timezone(GMT+3):
var strDate = "2020-07-10 04:00:00+0000"
var result: Date?
var dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ")
dateFormatter.timeZone = TimeZone.getTimeZone("Asia/Jerusalem")
result = dateFormatter.parse(strDate)
The problem is result always return "Fri Jul 10 11:00:00 GMT+07:00 2020"
But I expected it will return date object "Fri Jul 10 07:00:00 GMT+03:00 2020", any idea what's wrong with my code?
It's recommended to use java.time and stop using java.util.Date, java.util.Calendar along with java.text.SimpleDateFormat because of problems like this one.
In your code, the target time zone is obviously not applied to the date but it isn't obvious why it isn't.
A different problem might be pattern you are using because your example String does not contain any unit of time smaller than seconds but the pattern tries to consider .SSS (which made the code fail in the Kotlin Playground).
Switch to java.time and handle this with modern classes, such as OffsetDateTime for parsing this String (it doesn't contain information about a specific time zone, just an offset of zero hours) and ZonedDateTime as the target object (this considers a real time zone which may have different offsets depending things like Daylight Saving Time).
You could do it like this:
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
fun main() {
// this example is in UTC (+0000 --> no offset / offset of 0 hours)
var strDate = "2020-07-10 04:00:00+0000"
// create a formatter that can parse Strings of this pattern
// ([] represents optional units to be parsed)
var dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss[.SSS]Z")
// and parse the String to an OffsetDateTime using this formatter
var resultOfParsing = OffsetDateTime.parse(strDate, dateFormatter)
// then print the parsed result
println(resultOfParsing)
// create the target time zone
var timeZone = ZoneId.of("Asia/Jerusalem")
// then use the target zone for a zone shift
var jerusalemTime: ZonedDateTime = resultOfParsing.atZoneSameInstant(timeZone)
// and print the result
println(jerusalemTime)
// you could use your formatter defined above for a differently formatted output, too
println(jerusalemTime.format(dateFormatter))
}
which outputs (including all intermediate results):
2020-07-10T04:00Z
2020-07-10T07:00+03:00[Asia/Jerusalem]
2020-07-10 07:00:00.000+0300

How do you compare selector attributes in Testcafe?

I'm trying to compare the date of videos on a webpage to today's date. If the difference between the two dates is more than X days, report back as false.
The videos on the webpage have a tag in them which uses the format yyyy-mm-dd
I've got a selector set up to find the videos const videoDate = Selector('OPTA-video').withAttribute('data-secondary-time')
Now how do I set a variable to today's date and compare the two? I'm completely stuck!
I was using Katalon Studio before and here's the groovy script that did the same job:
String videoDate = WebUI.getAttribute(findTestObject('OPTA-video'), 'data-secondary_time')
LocalDate todaysDate = LocalDate.now()
LocalDate videoDateParsed = LocalDate.parse(videoDate, dtf)
if (ChronoUnit.DAYS.between(videoDateParsed, todaysDate) > 1) {
KeywordUtil.markFailed('The videos are 2+ days old.')
} else {
KeywordUtil.logInfo('The videos are up to date.')
}
You can use the getAttribute TestCafe method to access an attribute value. Then, parse the attribute value into the JavaScript Date object:
String videoDate = Selector('OPTA-video').getAttribute('data-secondary-time');
Date videoDateParsed = Date.parse(videoDate);
Date todaysDate = Date.now()
...
In the following thread you can find how to compare Date objects.
This is one of the scripts that I am using.
//getting your XPath test value into a string
String ann_time =
WebUI.getText(findTestObject("ObjectRepository/navigateTOElement/announcements_date"))
//converting time to simple date format
SimpleDateFormat sdf = new SimpleDateFormat('HH:mm')
Date sdf_anntime = sdf.parse(new String(ann_time))
//getting Current time
SimpleDateFormat dateFormatGmt = new SimpleDateFormat('HH:mm')
dateFormatGmt.setTimeZone(TimeZone.getTimeZone('GMT'))
SimpleDateFormat dateFormatLocal = new SimpleDateFormat('HH:mm')
currDate = dateFormatLocal.parse(dateFormatGmt.format(new Date()))
// time gap in long format
long duration = currDate.getTime() - sdf_anntime.getTime()
//time gap to mins
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration)
//compare time gap with globale variable
if (diffInMinutes < GlobalVariable.News_updated_time) {
log.logInfo("system is getting updated,last updated "+ diffInMinutes + "min ago")
} else {
CustomKeywords.'errorMessage.logFailed.markStepFailed'('from 1 h, system was not updated')
log.logInfo('from '+ diffInMinutes+ 'h, system was not updated')
}